Course contentsShow
← C#
Lesson 1029 of 1,90810. Entity Framework Core ModelingFree lesson

Fluent API Mapping Strategies

Centralize model configuration outside of entity classes using the Fluent API.

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:

  1. 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");
    }
}
  1. Apply it in DbContext: Instead of writing every rule manually in OnModelCreating, 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.