skip to content

In EF Core, what is a shadow property, how do you configure, set and query one, and when does EF create one without being asked?

level: seniorimportance: should knowfreq 38%

answer

  1. in the model, not in the class
  2. value lives in the change tracker
  3. Property<DateTime>("LastUpdated")
  4. EF.Property<T>(entity, name) in LINQ
  5. convention-made foreign keys

basics

~20 s

A shadow property is a column EF Core maps without a matching CLR property: it exists in the model and its value lives in the change tracker. Configure it with Property<T>("Name"), set it through Entry(...).Property("Name"), and query it with EF.Property<T>.

solid answer

~40 s

A shadow property is defined in the EF Core model but not on the entity class; its value and state are kept by the change tracker. `builder.Property<DateTime>("LastUpdated")` creates one when the class has no member of that name. You set or read it through `context.Entry(title).Property("LastUpdated").CurrentValue`, often in a `SaveChangesAsync` override that stamps audit columns for every `Added` or `Modified` entry, and you query it with `EF.Property<DateTime>(t, "LastUpdated")` inside LINQ. Values are unavailable for entities from a no-tracking query, because nothing tracks them. EF creates shadow properties itself mostly for foreign keys: when a navigation exists but no foreign key property is found, conventions add one such as `PublisherId`.

code

csharp · 13 lines
csharp
public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
    var now = DateTime.UtcNow;
    foreach (var entry in ChangeTracker.Entries<Title>())
    {
        if (entry.State is EntityState.Added or EntityState.Modified)
        {
            entry.Property("LastUpdated").CurrentValue = now;
            entry.Property("UpdatedBy").CurrentValue = _currentUser.Login;
        }
    }
    return base.SaveChangesAsync(cancellationToken);
}

go deeper

for a junior

Recall that a shadow property is a mapped column with no class property, configured with Property<T>("Name").

for a middle

Explain where the value lives, how Entry(...).Property(...) and EF.Property<T> reach it, and the convention-made foreign key case.

for a senior

Design audit stamping with shadow properties in a SaveChangesAsync override, and catch accidental shadow foreign keys and no-tracking surprises.

for a principal

Judge which persistence facts belong out of the domain model as shadow properties and which the domain genuinely needs to see.

## The idea An EF Core **model** describes columns as properties of entity types. Usually each model property is backed by a CLR property on the class. A **shadow property** is a model property with **no CLR member**: EF knows the column exists, includes it in `SELECT`, `INSERT` and `UPDATE` statements, and keeps its **value and state in the change tracker** instead of in the object. Shadow properties suit data that belongs in the table but not in the domain class. A legacy bookstore table carrying `ROW_UPD_TS` and `ROW_UPD_BY` audit columns is the typical case: the database needs them, the `Title` class should not expose them. ## Configuring one Shadow properties are configured with the **fluent API** through the string overload of `Property`: ```csharp builder.Property<DateTime>("LastUpdated").HasColumnName("ROW_UPD_TS"); builder.Property<string>("UpdatedBy").HasColumnName("ROW_UPD_BY").HasMaxLength(30); ``` Rules worth knowing: - if the name matches an existing CLR property or shadow property, the call **configures that property** instead of creating a new one; - for a name with no CLR property, EF looks for a **field** of that name before falling back to a shadow property; - everything you can chain on a normal property (`IsRequired`, `HasDefaultValueSql`, `HasMaxLength`) works on a shadow property. There is no attribute for a shadow property, since there is no member to put it on. ## Setting and reading values Because the value lives in the change tracker, you reach it through an **entry**: ```csharp context.Entry(title).Property("LastUpdated").CurrentValue = DateTime.UtcNow; ``` The usual pattern stamps audit columns centrally: 1. Override `SaveChangesAsync` in the context. 2. Loop over `ChangeTracker.Entries()` and pick entries in state `Added` or `Modified`. 3. Set `entry.Property("LastUpdated").CurrentValue` and `entry.Property("UpdatedBy").CurrentValue`. 4. Call the base `SaveChangesAsync`. ## Querying Inside LINQ, refer to a shadow property with the static **`EF.Property<TProperty>(object entity, string propertyName)`** method, which EF translates to the column: ```csharp var stale = await context.Titles .Where(t => EF.Property<DateTime>(t, "LastUpdated") < cutoff) .OrderBy(t => EF.Property<DateTime>(t, "LastUpdated")) .ToListAsync(); ``` Projecting it works too: `Select(t => new { t.Name, Updated = EF.Property<DateTime>(t, "LastUpdated") })`. One restriction: entities returned by a **no-tracking** query are not in the change tracker, so their shadow values cannot be read through `Entry` afterwards. Project the value in the query instead. ## When EF creates one for you The most common shadow properties are created by **conventions** for **foreign keys**. If `Title` has a `Publisher` navigation but no `PublisherId` property, EF adds a shadow `PublisherId` to hold the foreign key column. The name is built from the navigation name and the principal key name. This is convenient, but it also means a missing or misspelled foreign key property silently becomes a shadow property, which `context.Model.ToDebugString()` reveals. ## When to choose a shadow property A shadow property is a design choice, not just a mapping trick. It fits when: - the column is **infrastructure**, such as audit timestamps, row version stamps maintained elsewhere, or a tenant column applied by a query filter, and domain code should never set it by hand; - the value is **set centrally**, in a `SaveChangesAsync` override or an interceptor, so no business method needs it; - the entity is **shared** between contexts and only one of them maps the extra column. It fits badly when domain logic reads the value, when the entity is often loaded with `AsNoTracking()` and the value is needed afterwards, or when the column is part of the public API's response. In those cases a normal property, perhaps with a private setter and a backing field, is simpler to read and test. ## Shadow properties compared | | CLR property | Shadow property | Field-only property | |---|---|---|---| | Value stored in | The object | The change tracker | A private field on the object | | Visible to domain code | Yes | No | Only inside the class | | Survives a no-tracking query | Yes | No | Yes | | Queried with | The property | `EF.Property<T>` | `EF.Property<T>` | ## Pitfalls - Expecting a shadow value on an entity loaded with `AsNoTracking()`. - Attaching a detached entity with `Update`: every property, shadow ones included, is marked modified, so unset shadow values can overwrite audit columns with defaults. - Mistyping the string name: `EF.Property<DateTime>(t, "LastUpdate")` fails at query translation because no such property exists in the model.

  • Why can't you read a shadow property's value after an AsNoTracking query?
    A shadow property's value lives only in the change tracker's entry for that entity. A no-tracking query materialises objects without creating entries, and the object itself has no member to hold the value. Project the column in the query with `EF.Property<T>(t, "LastUpdated")` when you need it read-only.
  • How would you spot a foreign key that became a shadow property by accident?
    Print `context.Model.ToDebugString()` and look for properties marked as shadow, or watch the migration: a misspelled `PublisherID` property alongside a convention-made `PublisherId` produces two columns. Naming the foreign key property explicitly in the relationship configuration removes the shadow one.

  • A shadow property is stored in a hidden private field generated by EF.
  • A shadow property is declared by marking a class property with [NotMapped].
  • You can read a shadow value on an entity loaded with AsNoTracking().
  • Shadow properties cannot be used in Where or OrderBy clauses.
  • EF never creates shadow properties unless you configure them.