Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 41 ยท DbContext and Models

Data Annotations and the Fluent API

Configure EF Core models with data annotations and the fluent API - required, max length, precision, table and column names, indexes - plus IEntityTypeConfiguration and the order of precedence.

Conventions get you started, but real models need more: a maximum length for a name, a precision for money, a unique index on an email, a table name that matches an existing schema. EF Core gives you two ways to say so: data annotations (attributes on the class) and the fluent API (code in OnModelCreating). Both feed the same model; the fluent API can express everything and wins when both disagree.

This lesson shows both styles side by side, how to organize configuration in separate classes, and which style to choose. All EF Core code here is read-only; the stand-ins let you practise the idea of layered configuration.

Data annotations

Attributes live in System.ComponentModel.DataAnnotations and ...Schema. They are short and sit next to the property:

C#
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

[Table("products")]
public class Product
{
    public int Id { get; set; }

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

    [Column(TypeName = "decimal(10,2)")]
    public decimal Price { get; set; }

    [NotMapped]
    public string DisplayName => $"{Name} (${Price})";

    [Timestamp]
    public byte[] RowVersion { get; set; } = [];
}

Common attributes: [Key], [Required], [MaxLength]/[StringLength], [Column], [Table], [NotMapped], [ForeignKey], [Index], [Precision] and [Timestamp]. Many of them (Required, MaxLength, StringLength) are also read by ASP.NET Core model validation, which is a benefit when the entity is also your input model, and a risk when you want the two concerns separate.

The fluent API

The fluent API is code inside OnModelCreating. It is more verbose but complete, and it keeps your entities free of persistence attributes:

C#
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Product>(entity =>
    {
        entity.ToTable("products");
        entity.HasKey(p => p.Id);

        entity.Property(p => p.Name)
              .IsRequired()
              .HasMaxLength(120);

        entity.Property(p => p.Price)
              .HasPrecision(10, 2);

        entity.Property(p => p.RowVersion).IsRowVersion();

        entity.Ignore(p => p.DisplayName);

        entity.HasIndex(p => p.Name).IsUnique();
    });
}

Things only the fluent API can do (or does best): composite indexes with options, relationship details (delete behavior, join tables), inheritance mapping, query filters, value converters, default values via SQL (HasDefaultValueSql("GETDATE()")), and sequences.

Precedence

When rules overlap, the more explicit one wins:

  1. Conventions (lowest)
  2. Data annotations
  3. Fluent API (highest)

So [MaxLength(50)] plus .HasMaxLength(80) gives 80. EF Core also tracks how something was configured (convention, data annotation, explicit) so a convention never overrides your choice.

Three layers of configuration

Conventions Defaults
Annotations Attributes
Fluent API Always wins

Later layers override earlier ones

1 / 2

Keep configuration organized

Dozens of entities make OnModelCreating unreadable. Move each entity's configuration into its own class:

C#
public class ProductConfiguration : IEntityTypeConfiguration<Product>
{
    public void Configure(EntityTypeBuilder<Product> builder)
    {
        builder.ToTable("products");
        builder.Property(p => p.Name).IsRequired().HasMaxLength(120);
        builder.Property(p => p.Price).HasPrecision(10, 2);
        builder.HasIndex(p => p.Name).IsUnique();
    }
}

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

ApplyConfigurationsFromAssembly finds every IEntityTypeConfiguration<T> and applies it, so adding an entity never means editing the context.

You can also set rules for all properties of a kind in one place, which is invaluable for decimals:

C#
protected override void ConfigureConventions(ModelConfigurationBuilder builder)
{
    builder.Properties<decimal>().HavePrecision(18, 2);
    builder.Properties<string>().HaveMaxLength(200);
}

Which style should you use?

There is no single correct answer. A practical rule that many teams settle on:

  • Use the fluent API (in IEntityTypeConfiguration classes) for everything persistence-related. Entities stay plain C#, and you have one place to look.
  • Use annotations only if you share the class with validation and want one source of truth, and accept the mixing.
  • Use ConfigureConventions for rules that should apply everywhere.

Pick one approach per project and be consistent; mixing both for the same property is how people end up debugging which layer won.

Stand-in: layered configuration

The stand-in is not EF Core. It models how a property's settings are resolved from three layers, so you can see why the fluent value wins.

C# Stand-in: conventions, annotations and fluent layers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Stand-in: validate a model against its rules

Annotations like [Required] and [MaxLength] are also used by validators. This stand-in uses the real System.ComponentModel.DataAnnotations validator, which is part of the base library and therefore runs here. (EF Core itself does not validate on SaveChanges; the database rejects violations. Use a validator in your application layer.)

C# Validate annotations with Validator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. If a property has [MaxLength(50)] and the fluent API says HasMaxLength(80), what is the result?

    The fluent API has the highest precedence, above annotations and conventions.
  2. 2. Which can only be done (or done fully) with the fluent API?

    Delete behavior, join tables, inheritance and many other settings need the fluent API.
  3. 3. What does ApplyConfigurationsFromAssembly do?

    It scans an assembly for configuration classes so OnModelCreating stays short.
  4. 4. Does EF Core validate [Required] when you call SaveChanges?

    EF Core uses the attribute to build the model (NOT NULL), but model validation messages come from ASP.NET Core or your own Validator calls.

Summary

  • Annotations are short attributes; the fluent API is complete and has the final say.
  • Precedence: convention < annotation < fluent API.
  • Use IEntityTypeConfiguration<T> classes and ApplyConfigurationsFromAssembly to organize.
  • ConfigureConventions sets rules for all properties of a type, such as decimal precision.
  • Choose one primary style per project and keep entity classes persistence-free where you can.

Next: Keys and Generated Values