Entity Framework Core Beginner

Entities, conventions, data annotations and Fluent API

EF Core builds its picture of your database, the model, from your C# classes. This lesson shows the conventions it follows on its own, and the two ways to change them: data annotation attributes on the class and the Fluent API in OnModelCreating.

How EF Core builds the model
  1. ConventionsNames, keys and types from your classes
  2. Data annotationsAttributes such as [Required] and [MaxLength]
  3. Fluent APIOnModelCreating overrides everything above
  4. The modelUsed for queries, SaveChanges and migrations

Conventions: what EF Core does by itself

  • A DbSet<Product> property makes Product an entity; the table is named after the DbSet (Products).
  • A property named Id or ProductId becomes the primary key; int and long keys become IDENTITY columns.
  • Non-nullable C# types (int, decimal, and string with nullable reference types on) become NOT NULL columns.
  • A property such as CategoryId next to a Category navigation becomes the foreign key.
  • string becomes nvarchar(max) unless you set a maximum length.

Data annotations

Attributes on the class are quick and also drive MVC validation messages. They cover the common cases.

C#
public class Product
{
    public int Id { get; set; }

    [Required, MaxLength(200)]
    public string Name { get; set; } = "";

    [Precision(18, 2)]
    public decimal Price { get; set; }

    [Column("sku"), Unicode(false), MaxLength(20)]
    public string Sku { get; set; } = "";

    public int CategoryId { get; set; }
    public Category Category { get; set; } = null!;
}

Fluent API

The Fluent API can configure everything annotations can, and more: composite keys, indexes, default values, relationships and table splitting. It keeps the entity classes clean. Put each entity's setup in its own configuration class.

C#
public class ProductConfiguration : IEntityTypeConfiguration<Product>
{
    public void Configure(EntityTypeBuilder<Product> b)
    {
        b.ToTable("Products");
        b.Property(p => p.Name).HasMaxLength(200).IsRequired();
        b.Property(p => p.Price).HasPrecision(18, 2);
        b.HasIndex(p => p.Sku).IsUnique();
        b.Property<DateTime>("CreatedAt").HasDefaultValueSql("SYSUTCDATETIME()"); // shadow property
    }
}

// In the DbContext
protected override void OnModelCreating(ModelBuilder modelBuilder)
    => modelBuilder.ApplyConfigurationsFromAssembly(typeof(ShopContext).Assembly);

Which to use

When both are used, the Fluent API wins. Many teams use annotations for simple rules that the UI also needs (Required, MaxLength) and the Fluent API for database-only details (indexes, precision, relationships).

ConfigureConventions lets you set defaults for every property of a type at once, for example all decimals to precision 18,2 and all strings to a max length.

Interview question

What is the difference between data annotations and the Fluent API in EF Core?

Both configure the model. Data annotations are attributes on entity classes, easy to read and shared with validation, but limited. The Fluent API is code in OnModelCreating or IEntityTypeConfiguration classes that can configure everything, including composite keys, indexes and relationships, and keeps entities free of persistence details. When both set the same thing, the Fluent API wins.

Your progress is saved only in this browser.

Want the full details? Read the official Microsoft documentation for this topic.