In this lesson, you will learn how to keep your domain models clean and focused by mapping database columns that don't exist as properties in your C# classes.
The Problem: Pollution of the Domain
In domain-driven design, your entity classes should represent business concepts, not database schema requirements. Often, we want to track metadata like LastUpdated or InternalAuditId in the database, but we don’t want our business logic (or our unit tests) to be cluttered with properties that don't serve a behavioral purpose. If a property is strictly for infrastructure concerns, it’s a form of "leaky abstraction" to force it into your entity class.
The Solution: Shadow Properties
EF Core allows you to define "Shadow Properties." These are columns that exist in your database schema, but are managed entirely through the DbContext or the ChangeTracker. Your C# class remains blissfully unaware of their existence.
You configure these in your OnModelCreating method using the Fluent API:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>()
.Property<DateTime>("LastUpdated") // This property does not exist in Product.cs
.HasDefaultValueSql("GETDATE()");
}
Working with Hidden Data
Since these properties don't exist on your entity, you cannot access them via dot-notation (e.g., myProduct.LastUpdated). Instead, you use the ChangeTracker API to get or set their values:
// Setting the shadow property value
context.Entry(myProduct).Property("LastUpdated").CurrentValue = DateTime.Now;
// Reading the shadow property value
var updatedTime = context.Entry(myProduct).Property("LastUpdated").CurrentValue;
By moving infrastructure concerns into the database mapping layer, you keep your domain entities slim, focused, and free from database-specific metadata. This ensures that your business logic remains pure and untainted by the mechanics of persistence.
Key Takeaway: Shadow properties allow you to map database columns that exist strictly for infrastructure purposes without polluting your domain model with non-behavioral properties.