📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

πŸ“š Interview question

What are shadow properties and backing fields in EF Core? When would you use each, and how do you map an aggregate that exposes a read-only collection while EF Core still loads and saves it?

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.

Mid-Level Theory Intermediate aggregates backing-fields ddd ef-core encapsulation shadow-properties

🎯 Key points

  • Shadow property: in the model and table, not on the CLR class; values live in the change tracker
  • Configure with builder.Property<T>("Name"); read in LINQ with EF.Property<T>(e, "Name")
  • Set them centrally: SaveChangesInterceptor or SaveChanges override via Entry(e).Property("Name").CurrentValue
  • Typical uses: audit columns, TenantId for multi-tenant filters, IsDeleted for soft delete, FKs without a CLR property
  • Backing field: EF reads/writes _field instead of the property (convention _name, m_name; HasField for others)
  • Encapsulated collection: private List<T> _lines + IReadOnlyCollection<T> Lines
  • UsePropertyAccessMode(PropertyAccessMode.Field) and constructor binding allow private setters

⏱ 30-second answer

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.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"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 use EF.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 a Customer navigation without a CustomerId property, 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 _status for a Status property and, since EF Core 3, reads and writes the field directly, bypassing setter logic during materialisation. The DDD case is an Order aggregate with private readonly List<OrderLine> _lines = [] and a public IReadOnlyCollection<OrderLine> Lines => _lines.AsReadOnly(). Callers can't Add to the collection; they call order.AddLine(product, quantity), which enforces the rules, like a maximum of 50 lines or no duplicate products. EF Core populates _lines when I Include the lines and detects added lines on save.

For example, at [company] we moved CreatedBy and TenantId into shadow properties set by a SaveChangesInterceptor, 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 properties vs backing fields

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

Property access modes

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

Production example

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.

πŸ” What the interviewer is checking

Checks whether the candidate can keep a domain model encapsulated while persisting it with EF Core.

Green flags

  • Explains where shadow values are stored
  • Uses EF.Property in queries
  • Maps a private collection with IReadOnlyCollection<T>
  • Knows setters are bypassed during materialisation

Red flags

  • Thinks EF Core requires public setters on everything
  • Uses shadow properties for core business data

πŸ“š Learn in depth

1. Where shadow values live

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.

2. Initialising and managing shadow values

  • On insert/update: a 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.
  • In filters: HasQueryFilter(o => EF.Property<Guid>(o, "TenantId") == _tenantId) or !EF.Property<bool>(o, "IsDeleted").
  • Defaults: HasDefaultValueSql("SYSUTCDATETIME()") lets the database fill a shadow column when nothing sets it.
  • Seeding: HasData must supply shadow values with an anonymous object, e.g. new { Id = 1, TenantId = ... }.

3. How EF Core finds and configures backing fields

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.

4. Encapsulated collections

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).

5. Constructors

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.

Try it yourself

  1. Add a shadow CreatedAt, set it in a SaveChangesInterceptor, and query by it with EF.Property.
  2. Run the same query with AsNoTracking() and check whether you can read the value.
  3. Build an Order with a private _lines list and an AddLine method; load it with Include and add a line.
  4. Rename the field to _orderLines, see what breaks, then fix it with HasField.
  5. Remove a line from _lines and inspect the SQL that SaveChanges produces.

πŸ’» Code

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

⚠ Common mistakes

  • Mistake: Putting business data in shadow properties. Why it is wrong: it is invisible in the domain and in no-tracking results. Instead: keep shadow properties for cross-cutting columns.
  • Mistake: Exposing List<T> with a public setter on an aggregate. Why it is wrong: anyone can bypass invariants. Instead: private field + IReadOnlyCollection<T> + methods.
  • Mistake: Returning _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.
  • Mistake: Expecting setter logic to run when EF Core loads an entity. Why it is wrong: EF Core writes the backing field by default. Instead: put invariants in methods, not setters, or use PropertyAccessMode.Property.
  • Mistake: Forgetting shadow FKs when writing raw SQL or projections. Why it is wrong: the column exists but nobody sets it. Instead: document shadow properties in the configuration class.
  • Mistake: Naming a field lines_ or theLines. Why it is wrong: the convention won't find it. Instead: _lines or HasField.

πŸ› Senior insight: trade-offs

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.

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions audit columns as shadow properties. Why: Checks practical use of shadow properties with interceptors.
    How to answer

    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.

  2. When: Candidate mentions encapsulation or private setters. Why: Checks knowledge of constructor binding and field access.
    How to answer

    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.

πŸ›  Real-world problems: how you handle them

Order totals drift because callers mutate the lines collection directly
Situation
An ordering service at [company] with [200k] orders a month exposed `List<OrderLine> Lines { get; set; }` on the `Order` entity; several handlers added lines directly.
Signals
Finance reported [about 20] invoices a month whose total didn't match the sum of their lines; no exceptions in logs.
Investigation
Queried for orders where `Total <> SUM(lines)` to size the problem. Searched the codebase for `.Lines.Add(` and found [3] handlers that skipped the total recalculation. Confirmed with EF Core logging that the UPDATE for `Total` was missing in those paths.
Resolution
Immediate: a one-off script recalculated affected totals after finance sign-off. Real fix: changed `Order` to a private `_lines` field with `IReadOnlyCollection<OrderLine> Lines` and an `AddLine` method that recalculates `Total`; the compiler then flagged every direct mutation.
Prevention
An architecture test (NetArchTest) that fails if aggregate collections expose public mutable types; integration tests with Testcontainers covering add/remove lines; a nightly reconciliation query with an alert.

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.

More in EF Core Fundamentals

Last updated 23 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me