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

Domain-Driven Design with EF Core

Align the persistence layer with bounded contexts and domain-driven design principles.

In this lesson, you will learn how to align your EF Core persistence layer with the strategic boundaries defined in Domain-Driven Design (DDD).

In DDD, a Bounded Context defines the explicit boundary within which a particular domain model exists. A common mistake is to treat your DbContext as a single, monolithic bucket for the entire application. When working with DDD, your persistence layer should instead reflect the business context, ensuring that entities are protected from leaking data or logic into unrelated areas of the system.

Encapsulating Domain Boundaries

To align EF Core with DDD, avoid exposing your internal domain logic to the database schema. Use Backing Fields and private setters to force interaction through domain methods rather than property setters. This ensures that the DbContext remains a persistence-only mechanism that respects your domain invariants.

Consider an Order aggregate:

public class Order
{
    private decimal _totalAmount; // Backing field

    // Private setter forces the use of domain methods
    public decimal TotalAmount => _totalAmount;

    public void ApplyDiscount(decimal discount)
    {
        if (discount > 0) _totalAmount -= discount;
    }
}

In your EntityTypeConfiguration, you tell EF Core to map directly to this field:

builder.Property(o => o.TotalAmount)
       .HasField("_totalAmount")
       .AccessMode(PropertyAccessMode.Field);

Strategic Alignment

When dealing with multiple Bounded Contexts, you should ideally have separate DbContext instances if the contexts are significantly different. For example, the Ordering context and the Catalog context likely have different requirements for what an "Item" looks like. By keeping these DbContexts separate, you prevent the "Shared Database" anti-pattern where a change in the Catalog schema inadvertently breaks your Ordering logic.

By configuring EF Core to treat the database as a secondary infrastructure detail—rather than the source of truth for your business rules—you maintain a clean separation between the persistence technology and your core domain model.

Key Takeaway: Align your EF Core models by using private backing fields to enforce domain invariants and separate DbContexts to respect the boundaries of your Bounded Contexts.