Covers EF Core shadow properties (EF.Property, audit and FK uses), backing fields and property access modes, and mapping encapsulated read-only collections in DDD aggregates.
A shadow property exists in the EF Core model and the table but not on your class; its value lives in the change tracker. You declare it with builder.Property<DateTime>("CreatedAt"), read it in LINQ with EF.Property<DateTime>(o, "CreatedAt"), and set it centrally, usually in a SaveChangesInterceptor through Entry(o).Property("CreatedAt").CurrentValue. Good for audit columns, a TenantId behind a multi-tenant query filter, an IsDeleted soft-delete flag, or foreign keys you don't want on the domain object.
A backing field is a private field EF Core reads and writes instead of the property, found by convention (_status for Status) or set with HasField. It is how you map a DDD aggregate that exposes IReadOnlyCollection<OrderLine> Lines over a private List<OrderLine> _lines, so callers must use AddLine() and the invariants hold.
The trade-off: both keep persistence details out of the domain, but values you can't see on the class are easier to forget in tests and projections.
"A shadow property is a column EF Core knows about that has no property on my class. I declare it with
builder.Property<DateTime>("CreatedAt"), the migration creates the column, and the value is stored in the change tracker entry rather than in the object. I useEF.Property<DateTime>(order, "CreatedAt")to filter or sort by it in LINQ, and an interceptor sets it on save. EF Core also creates shadow properties itself: if I have aCustomernavigation without aCustomerIdproperty, the FK becomes a shadow property.Backing fields solve a different problem: I want the class to protect its state, but EF Core still has to load and save it. By convention EF Core finds
_statusfor aStatusproperty and, since EF Core 3, reads and writes the field directly, bypassing setter logic during materialisation. The DDD case is anOrderaggregate withprivate readonly List<OrderLine> _lines = []and a publicIReadOnlyCollection<OrderLine> Lines => _lines.AsReadOnly(). Callers can'tAddto the collection; they callorder.AddLine(product, quantity), which enforces the rules, like a maximum of 50 lines or no duplicate products. EF Core populates_lineswhen IIncludethe lines and detects added lines on save.For example, at [company] we moved
CreatedByandTenantIdinto shadow properties set by aSaveChangesInterceptor, which removed [30] places where developers set them by hand and could forget. The mistake I see with shadow properties is projecting to DTOs and forgetting they exist, or tests that use an in-memory list and can't see them. So I keep them for genuinely cross-cutting columns, not for business data."
| Shadow property | Backing field | |
|---|---|---|
| On the CLR class? | No | Yes, as a private field |
| Where the value lives | Change tracker entry | The object |
| Read in LINQ | EF.Property<T>(e, "Name") |
The public property |
| Typical use | Audit, tenant id, hidden FKs | Encapsulation, read-only collections, validation in setters |
| Visible in no-tracking results | No (not on the object) | Yes |
| Mode | Reads/writes |
|---|---|
PreferField (default) |
Field when found, else property |
Field |
Always the field; throws if missing |
Property |
Always the property (setter logic runs) |
PreferFieldDuringConstruction |
Field while materialising, property afterwards |
In an ordering service, moving to an encapsulated Lines collection caught [3] code paths that added lines without recalculating the order total. The total became consistent, and a support issue that had produced [about 20] wrong invoices a month disappeared.
Checks whether the candidate can keep a domain model encapsulated while persisting it with EF Core.
Green flags
EF.Property in queriesIReadOnlyCollection<T>Red flags
Order object InternalEntityEntry (change tracker)
ββββββββββββββββ ββββββββββββββββββββββββββ
β Id, Status ββββββββββββ entity ref β
β _lines β β shadow values: CreatedAtβ
ββββββββββββββββ β original values snapshotβ
ββββββββββββββββββββββββββ
Because shadow values live in the entry, a no-tracking query has nowhere to put them: they can be filtered on in SQL but don't come back on the object. Project them explicitly if you need them.
SaveChangesInterceptor walks ChangeTracker.Entries(); for Added it sets CreatedAt/CreatedBy/TenantId, for Modified it sets ModifiedAt/ModifiedBy, and for Deleted (soft delete) it changes the state to Modified and sets IsDeleted = true.HasQueryFilter(o => EF.Property<Guid>(o, "TenantId") == _tenantId) or !EF.Property<bool>(o, "IsDeleted").HasDefaultValueSql("SYSUTCDATETIME()") lets the database fill a shadow column when nothing sets it.HasData must supply shadow values with an anonymous object, e.g. new { Id = 1, TenantId = ... }.The convention looks for fields named <camelCase>, _<camelCase>, _<PascalCase>, m_<camelCase> or m_<PascalCase>. For anything else:
b.Property(o => o.Status).HasField("_currentStatus"); // non-standard name
b.Property<string>("_internalNote").HasColumnName("Note"); // field-only, no property
b.Navigation(o => o.Lines).HasField("_orderLines")
.UsePropertyAccessMode(PropertyAccessMode.Field);
b.UsePropertyAccessMode(PropertyAccessMode.Property); // per entity: always use setters
Pitfalls: a property with only a getter and no discoverable field is not mapped at all (EF Core ignores it silently); renaming a field breaks the convention without a compile error; PropertyAccessMode.Field throws at model build if the field is missing, which is a useful safety net.
EF Core needs a mutable collection to add loaded entities to. When the navigation property returns IReadOnlyCollection<T>, EF Core uses the backing field _lines for loading and for detecting additions and removals. Removing an item from _lines orphans the line: with a required relationship and cascade, EF Core deletes it on save (DeleteOrphansTiming).
EF Core can bind to a constructor whose parameters match mapped property names, so entities can have private setters and no public parameterless constructor. Navigations can't be constructor parameters.
CreatedAt, set it in a SaveChangesInterceptor, and query by it with EF.Property.AsNoTracking() and check whether you can read the value.Order with a private _lines list and an AddLine method; load it with Include and add a line._orderLines, see what breaks, then fix it with HasField._lines and inspect the SQL that SaveChanges produces.An aggregate with an encapsulated collection and shadow audit columns.
namespace Ordering.Domain;
public sealed class Order
{
private readonly List<OrderLine> _lines = []; // EF Core loads and tracks this field
private Order() { } // for EF Core materialisation
public Order(int customerId) => CustomerId = customerId;
public int Id { get; private set; }
public int CustomerId { get; private set; }
public decimal Total { get; private set; }
public IReadOnlyCollection<OrderLine> Lines => _lines.AsReadOnly();
public void AddLine(int productId, int quantity, decimal unitPrice)
{
if (_lines.Count >= 50) throw new InvalidOperationException("An order can have at most 50 lines.");
if (_lines.Any(l => l.ProductId == productId)) throw new InvalidOperationException("Product already on the order.");
_lines.Add(new OrderLine(productId, quantity, unitPrice));
Total = _lines.Sum(l => l.Quantity * l.UnitPrice); // invariant kept in one place
}
}
public sealed class OrderLine(int productId, int quantity, decimal unitPrice)
{
public int Id { get; private set; }
public int ProductId { get; private set; } = productId;
public int Quantity { get; private set; } = quantity;
public decimal UnitPrice { get; private set; } = unitPrice;
}
namespace Ordering.Infrastructure;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Ordering.Domain;
public sealed class OrderConfiguration : IEntityTypeConfiguration<Order>
{
public void Configure(EntityTypeBuilder<Order> b)
{
b.Property<DateTime>("CreatedAt"); // shadow property
b.Property<string>("CreatedBy").HasMaxLength(100); // shadow property
b.HasMany(o => o.Lines).WithOne().HasForeignKey("OrderId"); // shadow FK on OrderLine
b.Navigation(o => o.Lines).UsePropertyAccessMode(PropertyAccessMode.Field);
b.Property(o => o.Total).HasPrecision(18, 2);
}
}
// Querying by a shadow property
// var recent = await db.Orders
// .Where(o => EF.Property<DateTime>(o, "CreatedAt") > cutoff)
// .ToListAsync(ct);
SELECT [o].[Id], [o].[CreatedAt], [o].[CreatedBy], [o].[CustomerId], [o].[Total]
FROM [Orders] AS [o]
WHERE [o].[CreatedAt] > @cutoff
List<T> with a public setter on an aggregate. Why it is wrong: anyone can bypass invariants. Instead: private field + IReadOnlyCollection<T> + methods._lines cast to IReadOnlyCollection<T> without AsReadOnly(). Why it is wrong: callers can cast back to List<T> and mutate it. Instead: AsReadOnly() or an immutable view.PropertyAccessMode.Property.lines_ or theLines. Why it is wrong: the convention won't find it. Instead: _lines or HasField.Shadow properties and backing fields are the two tools that let a rich domain model and EF Core coexist without leaking persistence concerns into the domain. Use them deliberately: backing fields for encapsulation (almost always worth it on aggregates), shadow properties for cross-cutting columns that infrastructure sets (audit, tenant, soft-delete flag).
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Shadow property | Audit, tenant id, hidden FKs set by interceptors | Invisible in code and no-tracking results | Data the domain reasons about |
| Backing field + read-only collection | Aggregates with invariants | A little more code | Simple CRUD DTO-like entities |
| Public setters everywhere | Prototypes, anaemic CRUD | Invariants scattered | Domain logic you care about |
Test the mapping with an integration test against SQL Server (Testcontainers), not the in-memory provider, so shadow FKs and field access are exercised for real.
Use a SaveChangesInterceptor (registered with AddInterceptors) that, in SavingChanges/SavingChangesAsync, walks ChangeTracker.Entries<IAuditable>() (or every entry that has the columns) and sets CreatedAt/CreatedBy for Added entries and ModifiedAt/ModifiedBy for Modified ones. Get the time from an injected TimeProvider so tests can fake it, and the user from a scoped ICurrentUser service that reads HttpContext.User (or the message's identity in a background worker). If you don't want audit fields on the domain classes, map them as shadow properties (builder.Property<DateTimeOffset>("CreatedAt")) and set them with entry.Property("CreatedAt").CurrentValue. Mark CreatedAt as not modified on updates so it can't be overwritten. Note that ExecuteUpdate and raw SQL bypass the interceptor; use temporal tables when you need full history, not just the last change.
EF Core does not need public setters or a public constructor. To create the object it uses constructor binding: it picks a constructor whose parameters match mapped scalar properties by name and type (camelCase name binds to Name), and passes the column values in. If none fits, it uses a parameterless constructor, which may be private. Any remaining mapped properties are set afterwards, through the backing field by default (_name or <Name>k__BackingField) or a private setter, so no domain logic in setters runs. Navigations can't be constructor parameters; they are fixed up after construction. This is the recommended way to keep DDD entities encapsulated, and it does not hurt change tracking: EF Core's default snapshot tracking compares values at DetectChanges, so it never relies on public setters. Only if you opt into notification tracking (INotifyPropertyChanged) must property changes raise events.
How to tell it (STAR)
**S:** In our ordering service at [company], finance found about [20] invoices a month where the total didn't match the lines. **T:** I owned the order domain and needed to stop the drift, not just patch the data. **A:** I sized the issue with a reconciliation query, found three handlers adding to the public `Lines` list without recalculating the total, and refactored `Order` so lines lived in a private backing field behind `IReadOnlyCollection` with an `AddLine` method. EF Core kept loading and saving the field, and the compiler pointed out every caller I had to fix. **R:** Mismatched invoices went to zero over the next [quarter], and an architecture test now stops anyone exposing a mutable collection on an aggregate again.
Last updated 23 Nov 2026.