Sub topic 13
Configuring the Model with Annotations and the Fluent API
So far, EF Core has built your database by following conventions. A convention is a default rule. For example, a property named Id or BlogId becomes the primary key, and a string property becomes a text column that may hold any length. Conventions save you work, but sometimes you need different rules. You might want a name that is required, a column with a size limit, or a value that must be unique.
This chapter shows the two ways to change the model:
- Data annotations, which are attributes you place on your entity classes.
- The Fluent API, which is a set of method calls you write inside your
DbContext.
The model is EF Core's internal description of your entities, their columns, keys, and rules. Migrations read the model to build the database, and queries use it to write SQL.
Why Configure the Model at All
Conventions guess what you want. Usually the guess is good. Here are some cases where you need to step in:
- A column should not allow empty (null) values.
- A text column should have a maximum length.
- Two rows should never share the same value, such as an email address.
- A property exists only in your C# code and should not become a column.
- A table or column needs a specific name, perhaps to match an existing database.
Style 1: Data Annotations
A data annotation is an attribute, written in square brackets above a property. Most of them live in the System.ComponentModel.DataAnnotations namespace.
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public class Author
{
public int Id { get; set; }
[Required, MaxLength(100)]
public string Name { get; set; } = "";
[Column("EmailAddress")]
public string? Email { get; set; }
[NotMapped]
public bool IsSelected { get; set; }
}Here is what each attribute does:
[Required]makes the column NOT NULL, so the database refuses rows without a value.[MaxLength(100)]sets the column's maximum length to 100 characters.[Column("EmailAddress")]gives the column a different name from the property.[NotMapped]tells EF Core to skip this property. No column is created for it.
Annotations are easy to read because the rule sits right next to the property it changes.
Style 2: The Fluent API
The Fluent API is a set of methods that you chain together, one after another. You write them in a method called OnModelCreating, which EF Core calls once while it builds the model. The method receives a ModelBuilder, an object you use to describe entities.
Some rules can only be written with the Fluent API. A unique index is one of them. An index is a lookup structure that helps the database find rows fast. A unique index also forbids duplicate values.
using Microsoft.EntityFrameworkCore;
public class LibraryContext : DbContext
{
public DbSet<Author> Authors => Set<Author>();
public DbSet<Book> Books => Set<Book>();
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlite("Data Source=library.db");
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Author>()
.HasIndex(a => a.Name)
.IsUnique();
modelBuilder.Entity<Book>(book =>
{
book.ToTable("LibraryBooks");
book.Property(b => b.Title)
.IsRequired()
.HasMaxLength(200);
book.Property(b => b.Price)
.HasPrecision(10, 2);
book.Ignore(b => b.IsOnSale);
});
}
}
public class Book
{
public int Id { get; set; }
public string Title { get; set; } = "";
public decimal Price { get; set; }
public bool IsOnSale { get; set; }
public int AuthorId { get; set; }
public Author Author { get; set; } = null!;
}The Book class has no attributes at all. Every rule for it is in OnModelCreating:
ToTable("LibraryBooks")names the table.IsRequired()andHasMaxLength(200)do the same job as[Required]and[MaxLength].HasPrecision(10, 2)stores up to 10 digits, with 2 after the decimal point.Ignoredoes the same job as[NotMapped].
Comparing the Two Styles
| Goal | Data annotation | Fluent API |
|---|---|---|
| Value must be present | `[Required]` | `.IsRequired()` |
| Limit text length | `[MaxLength(100)]` | `.HasMaxLength(100)` |
| Rename a column | `[Column("Name")]` | `.HasColumnName("Name")` |
| Rename a table | `[Table("Name")]` | `.ToTable("Name")` |
| Skip a property | `[NotMapped]` | `.Ignore(x => x.Prop)` |
| Set decimal size | `[Precision(10, 2)]` | `.HasPrecision(10, 2)` |
| Unique index | `[Index(nameof(Name), IsUnique = true)]` on the class | `.HasIndex(x => x.Name).IsUnique()` |
Annotations are short and visible. The Fluent API can express more rules, and it keeps your entity classes free of database details.
Which Rule Wins
You can mix both styles. When they disagree, EF Core follows a fixed order. Conventions apply first. Annotations override conventions. The Fluent API overrides both.
For example, if Name has [MaxLength(100)] and OnModelCreating says .HasMaxLength(50), the column gets a limit of 50.
Applying the Configuration
Configuration changes the model, so the database must catch up. Create and apply a migration, just as you learned earlier:
dotnet ef migrations add ConfigureLibraryModel
dotnet ef database updateOpen the generated migration file. You will see your rules turned into code, such as maxLength: 100, nullable: false, and a CreateIndex call with unique: true.
Seeing a Rule in Action
The unique index is enforced by the database. This program tries to add two authors with the same name:
using Microsoft.EntityFrameworkCore;
using var db = new LibraryContext();
db.Authors.Add(new Author { Name = "Ada Lovelace" });
await db.SaveChangesAsync();
db.Authors.Add(new Author { Name = "Ada Lovelace" });
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateException ex)
{
Console.WriteLine("Save failed: " + ex.InnerException?.Message);
}The first save works. The second save throws a DbUpdateException, and the inner message reports a UNIQUE constraint failure. Run the program a second time and the first save will fail too, because "Ada Lovelace" is already stored.
Keeping OnModelCreating Tidy
As your model grows, OnModelCreating can get long. You can move each entity's rules into its own class that implements IEntityTypeConfiguration<T>:
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
public class BookConfiguration : IEntityTypeConfiguration<Book>
{
public void Configure(EntityTypeBuilder<Book> book)
{
book.Property(b => b.Title).IsRequired().HasMaxLength(200);
}
}Then, inside OnModelCreating, one line loads every configuration class in the project:
modelBuilder.ApplyConfigurationsFromAssembly(typeof(LibraryContext).Assembly);Exercise
A property is marked [MaxLength(80)], and OnModelCreating calls .HasMaxLength(120) on the same property. What maximum length will the column have, and why?
Show answer
120. The Fluent API overrides data annotations, which in turn override conventions.
Exercise
You want a User entity where no two users can share the same Email value. Write the Fluent API code for OnModelCreating.
Show answer
modelBuilder.Entity<User>().HasIndex(u => u.Email).IsUnique(); Then add and apply a migration so the database creates the unique index.
Exercise
Your Order class has a property TotalWithTax that you calculate in C# and never want stored. Name two ways to stop EF Core from creating a column for it.
Show answer
Put the [NotMapped] attribute on the property, or call modelBuilder.Entity<Order>().Ignore(o => o.TotalWithTax) in OnModelCreating.