LESSON 9 OF 22

9. EF Core Entity Configuration and Relationship Mapping

Learn how to use Fluent API and separate configuration classes to define entity properties, keys, indexes, and relationships while keeping the Domain layer independent from EF Core.

50 dk 98

Introduction

In the previous lesson, we created the Infrastructure-layer DbContext and positioned EF Core in the application architecture. In this lesson, we will control how EF Core builds the database model. Instead of placing all mapping rules in one large OnModelCreating method, we will create a separate configuration class for each entity.

This is not only a code organization technique. In Clean Architecture, the more important goal is to keep Domain entities independent from EF Core, SQL Server, table names, column lengths, indexes, and delete behaviors. The Domain layer should express business concepts and invariants. Persistence-specific details should remain in Infrastructure.

For the examples, assume that our application contains products, categories, customers, orders, and order items. We will focus on Product, Category, Order, and OrderItem mappings.

Why use the Fluent API?

EF Core builds its model using conventions, data annotations, and the Fluent API. Conventions infer common rules from names and types. For example, a property named Id is normally discovered as a primary key. Conventions are useful, but they cannot express every business and database requirement explicitly.

Data annotations such as [Required], [MaxLength], and [Index] are convenient for small projects. However, adding persistence attributes directly to Domain entities introduces a dependency on EF Core concepts. That dependency weakens the separation between the business model and the infrastructure implementation.

The Fluent API keeps mapping code outside the Domain project and offers the most complete control over the EF Core model. It can configure table names, keys, indexes, property constraints, relationships, delete behaviors, precision, and provider-specific details.

Creating an entity configuration class

Create a configuration folder in the Infrastructure project:

Infrastructure
└── Persistence
    ├── ApplicationDbContext.cs
    └── Configurations
        ├── ProductConfiguration.cs
        ├── CategoryConfiguration.cs
        ├── OrderConfiguration.cs
        └── OrderItemConfiguration.cs

Each configuration class should implement IEntityTypeConfiguration<TEntity>. The Configure method contains all mapping rules for the selected entity.

using Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

public sealed class ProductConfiguration
    : IEntityTypeConfiguration<Product>
{
    public void Configure(EntityTypeBuilder<Product> builder)
    {
        builder.ToTable("Products");

        builder.HasKey(product => product.Id);

        builder.Property(product => product.Name)
            .IsRequired()
            .HasMaxLength(150);

        builder.Property(product => product.Description)
            .HasMaxLength(1000);

        builder.Property(product => product.Price)
            .HasPrecision(18, 2);

        builder.HasIndex(product => product.Name);
    }
}

ToTable defines the table name. HasKey explicitly selects the primary key. IsRequired prevents null values. HasMaxLength defines the maximum length of a string column. For monetary values, HasPrecision(18, 2) makes the intended SQL Server precision and scale explicit.

Applying configurations in DbContext

You can register configurations one by one:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.ApplyConfiguration(new ProductConfiguration());
    modelBuilder.ApplyConfiguration(new CategoryConfiguration());
    modelBuilder.ApplyConfiguration(new OrderConfiguration());
    modelBuilder.ApplyConfiguration(new OrderItemConfiguration());
}

As the number of entities grows, assembly scanning is more convenient:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.ApplyConfigurationsFromAssembly(
        typeof(ApplicationDbContext).Assembly);
}

This searches the Infrastructure assembly for classes implementing IEntityTypeConfiguration<T>. Configuration classes should have parameterless constructors. You should also avoid designs that depend on a particular configuration application order.

Required properties, column names, and indexes

When nullable reference types are enabled, non-nullable string properties are commonly treated as required. Nevertheless, explicitly configuring important database constraints makes the schema contract easier to understand and review.

builder.Property(category => category.Name)
    .HasColumnName("CategoryName")
    .IsRequired()
    .HasMaxLength(100);

builder.HasIndex(category => category.Name)
    .IsUnique();

This configuration requires a category name, limits it to 100 characters, and prevents duplicate names. However, not every index should be unique. Indexes can improve reads, but they also add storage overhead and make insert, update, and delete operations more expensive. Indexes should be selected according to real query patterns.

You can also define a composite index:

builder.HasIndex(order => new
{
    order.CustomerId,
    order.CreatedAt
})
.HasDatabaseName("IX_Orders_CustomerId_CreatedAt");

This index may help queries that retrieve orders for a customer and then filter or sort by creation time. Column order matters. If queries normally begin with CustomerId, putting that property first is generally more useful.

Configuring a one-to-many relationship

Assume that one category contains many products and each product belongs to one category. This is a one-to-many relationship. The Domain entities might look like this:

public sealed class Category
{
    public int Id { get; private set; }
    public string Name { get; private set; } = string.Empty;
    public ICollection<Product> Products { get; private set; }
        = new List<Product>();
}

public sealed class Product
{
    public int Id { get; private set; }
    public int CategoryId { get; private set; }
    public string Name { get; private set; } = string.Empty;
    public decimal Price { get; private set; }
    public Category Category { get; private set; } = null!;
}

Configure the relationship outside the Domain layer:

builder.HasOne(product => product.Category)
    .WithMany(category => category.Products)
    .HasForeignKey(product => product.CategoryId)
    .OnDelete(DeleteBehavior.Restrict);

HasOne says that a product has one category. WithMany says that a category has many products. HasForeignKey identifies the foreign key on the dependent entity. DeleteBehavior.Restrict prevents a category with products from being deleted.

For an order and its order items, cascading may be appropriate:

builder.HasOne(item => item.Order)
    .WithMany(order => order.Items)
    .HasForeignKey(item => item.OrderId)
    .OnDelete(DeleteBehavior.Cascade);

If an order is deleted, its line items may also be deleted because they have no independent business meaning. However, cascade behavior should never be selected automatically for every relationship. Customers, users, payments, and audit records often require restriction or soft deletion instead.

One-to-one and optional relationships

Consider a user with an optional profile record. The foreign key should be nullable when the relationship is optional:

builder.HasOne(user => user.Profile)
    .WithOne(profile => profile.User)
    .HasForeignKey<UserProfile>(profile => profile.UserId)
    .OnDelete(DeleteBehavior.Cascade);

When modeling optional relationships, check both the C# property type and the database behavior. An int? foreign key expresses that the relationship can be absent. If the business rule requires the relationship, using a nullable foreign key creates an inconsistent model.

Many-to-many relationships with a join entity

Suppose that a product can have many tags and a tag can be assigned to many products. This is a many-to-many relationship. EF Core can create a join table for simple cases. However, if the relationship needs additional data, such as the date a tag was assigned, create an explicit join entity.

public sealed class ProductTag
{
    public int ProductId { get; private set; }
    public int TagId { get; private set; }
    public DateTime AddedAtUtc { get; private set; }

    public Product Product { get; private set; } = null!;
    public Tag Tag { get; private set; } = null!;
}
builder.HasKey(productTag => new
{
    productTag.ProductId,
    productTag.TagId
});

builder.HasOne(productTag => productTag.Product)
    .WithMany(product => product.ProductTags)
    .HasForeignKey(productTag => productTag.ProductId)
    .OnDelete(DeleteBehavior.Cascade);

builder.HasOne(productTag => productTag.Tag)
    .WithMany(tag => tag.ProductTags)
    .HasForeignKey(productTag => productTag.TagId)
    .OnDelete(DeleteBehavior.Cascade);

builder.Property(productTag => productTag.AddedAtUtc)
    .IsRequired();

The composite primary key prevents the same tag from being assigned to the same product more than once. Using an explicit join entity also gives you control over relationship-specific fields and rules.

Validating the result with migrations

After creating the configurations, generate a migration and inspect how the model will be translated into the database:

dotnet ef migrations add ConfigureEntities \
    --project Infrastructure \
    --startup-project WebApi

dotnet ef database update \
    --project Infrastructure \
    --startup-project WebApi

Do not stop after creating the migration. Review nullable settings, string lengths, decimal precision, indexes, foreign keys, and delete actions. If EF Core creates an unexpected table or column, the cause is often an incorrectly configured navigation, a missing foreign key, or a nullable reference type mismatch.

Common mistakes

  • Adding EF attributes to Domain entities: This couples the Domain layer to persistence technology. Keep mapping rules in Infrastructure configuration classes.
  • Leaving every string unlimited: This can produce unnecessarily large columns and weak data-quality boundaries. Choose limits based on business requirements.
  • Adding indexes everywhere: Indexes improve some reads but increase write cost and storage usage.
  • Using cascade delete without analysis: Deleting one principal record may unexpectedly remove many dependent records.
  • Confusing navigations and foreign keys: A navigation represents the relationship in the object model; the foreign key represents the database connection.
  • Ignoring migration output: Successful compilation does not guarantee that the generated schema matches the intended design.

Short practice exercise

Create configuration classes for Category and Product with these rules:

  1. The category name is required and has a maximum length of 80 characters.
  2. The category name has a unique index.
  3. The product name is required and has a maximum length of 150 characters.
  4. The product price is stored as decimal(18,2).
  5. The product-category relationship is one-to-many.
  6. A category containing products cannot be deleted.
  7. Create a migration and inspect the generated schema changes.

Also consider whether Product.CategoryId requires an explicit index if product listing queries frequently filter by category. The decision should be supported by real query patterns, data volume, and execution plans rather than by habit.

Conclusion

In this lesson, we moved EF Core mapping into separate configuration classes. We configured primary keys, required properties, maximum lengths, decimal precision, indexes, and several relationship types using the Fluent API. We also saw why delete behavior must be selected together with business rules.

This structure allows Domain entities to represent the business model while table and column details remain inside Infrastructure. In the next lessons, we will use the resulting migrations, database schema, and repository queries in a more complete persistence workflow.

Sources