Sub topic 13
Configuring the Model with Annotations and the Fluent API
EF Core builds a picture of your database from your classes. This picture is called the model. The model says which tables exist, which columns they have, and what rules those columns follow. EF Core fills in most of it with conventions. A convention is a built-in default rule, such as "a property named Id is the primary key."
Sometimes the defaults are not what you want. For example, you might want a name that can never be empty, or one that is never longer than 100 characters. EF Core gives you two ways to change the model.
Two Ways to Configure
A data annotation is an attribute you place on a property. An attribute is a tag in square brackets, like [Required]. You write it right above the property it changes.
The Fluent API is a set of methods you call in code. You call them inside a method named OnModelCreating on your DbContext. The calls chain together, one after another.
Each step can override the one before it. If an annotation and the Fluent API disagree, the Fluent API wins.
A Worked Example
This code uses both styles together. The annotations make Name required and limit it to 100 characters. The Fluent API adds a unique index. A unique index is a database rule that stops two rows from having the same value in a column.
using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;
public class Author
{
public int Id { get; set; }
[Required, MaxLength(100)]
public string Name { get; set; } = "";
}
public class LibraryContext : DbContext
{
public DbSet<Author> Authors => Set<Author>();
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();
}
}The Fluent API can do everything the annotations did. This version of OnModelCreating produces the same model even with the attributes removed:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Author>(entity =>
{
entity.Property(a => a.Name)
.IsRequired()
.HasMaxLength(100);
entity.HasIndex(a => a.Name)
.IsUnique();
});
}Which Style Should You Pick?
| Need | Data annotations | Fluent API |
|---|---|---|
| Simple rules (required, max length) | Easy to read | Works too |
| Indexes and composite keys | Limited | Full support |
| Keep entity classes free of EF code | No | Yes |
| Overrides the other style | No | Yes |
A common habit is to use annotations for simple rules and the Fluent API for everything else.
Apply the Change
When you change the model, the database does not change by itself. You need to add a new migration and apply it:
dotnet ef migrations add AddAuthorRules
dotnet ef database updateExercise
You put [MaxLength(50)] on a property, and in OnModelCreating you call HasMaxLength(80) on the same property. What maximum length does the final model use, and why?
Show answer
It uses 80. EF Core applies the Fluent API after data annotations, so when the two disagree, the Fluent API setting wins.
Exercise
You add .IsUnique() to an index in OnModelCreating, but the database still accepts duplicate names. What step did you probably skip?
Show answer
You probably did not add and apply a new migration. Run dotnet ef migrations add with a name, then dotnet ef database update, so the database gets the new unique index.