Centralizing Fluent API Configurations
In this lesson, you will learn how to keep your domain entities clean by moving Entity Framework Core configuration logic into dedicated, centralized classes.
The Problem with Mixed Concerns
When you use Data Annotations or put all your OnModelCreating configuration directly inside the DbContext class, your code becomes cluttered. Your entity classes become "polluted" with infrastructure concerns, and your DbContext grows into a massive file that is difficult to navigate as your project scales.
The Solution: IEntityTypeConfiguration<T>
EF Core provides the IEntityTypeConfiguration<T> interface, which allows you to extract mapping logic into separate configuration classes. This follows the Single Responsibility Principle: your entity class manages state, while the configuration class manages how that state is mapped to the database.
Here is how you implement it:
- Create a Configuration Class:
public class UserConfiguration : IEntityTypeConfiguration<User>
{
public void Configure(EntityTypeBuilder<User> builder)
{
builder.HasKey(u => u.Id);
builder.Property(u => u.Username).IsRequired().HasMaxLength(50);
builder.ToTable("Users");
}
}
- Apply it in
DbContext: Instead of writing every rule manually inOnModelCreating, you can apply all configurations in the current assembly with a single line:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// This automatically scans the assembly for classes implementing IEntityTypeConfiguration
modelBuilder.ApplyConfigurationsFromAssembly(typeof(MyDbContext).Assembly);
}
Why This Matters
By centralizing your mapping, you avoid "leaking" database-specific constraints into your domain models. If you need to change a column name or update a relationship, you go to the UserConfiguration class rather than hunting through a bloated DbContext. This approach makes your infrastructure layer modular, testable, and significantly easier to maintain as your data schema evolves alongside your application.
Key Takeaway: Moving entity mapping into dedicated IEntityTypeConfiguration classes keeps your domain entities pure and your DbContext clean and maintainable.