Roadmap › Entity Framework (EF6 & EF Core) › Module: Getting Started
Lessons in this course (15)

4. Conventions, data annotations and Fluent API

Basic★ Must knowLesson 4 of 15

Configuration precedence: Fluent API > Data Annotations > Conventions.

csharp
// Data annotations
public class Product
{
    public int Id { get; set; }
    [Required, MaxLength(200)] public string Name { get; set; } = "";
    [Column(TypeName = "decimal(18,2)")] public decimal Price { get; set; }
    [Timestamp] public byte[] RowVersion { get; set; } = [];
}

// Fluent API (keeps entities clean; more powerful)
public class ProductConfig : IEntityTypeConfiguration<Product>
{
    public void Configure(EntityTypeBuilder<Product> b)
    {
        b.ToTable("Products", "catalog");
        b.HasKey(p => p.Id);
        b.Property(p => p.Name).IsRequired().HasMaxLength(200);
        b.Property(p => p.Price).HasPrecision(18, 2);
        b.HasIndex(p => p.Name).IsUnique();
        b.Property(p => p.RowVersion).IsRowVersion();
        b.HasQueryFilter(p => !p.IsDeleted);                  // global query filter (soft delete)
    }
}

Fluent-only features: composite keys (HasKey(x => new { x.A, x.B })), indexes, sequences, table splitting, owned types, value conversions, query filters, seed data (HasData), inheritance mapping.