skip to content

In EF Core, how do backing fields let an entity expose a read-only property or collection, and what does PropertyAccessMode change about how EF reads and writes it?

level: seniorimportance: should knowfreq 36%

answer

  1. _camelCase found by convention
  2. HasField or [BackingField]
  3. PreferField is the default
  4. setters skipped on materialisation
  5. IReadOnlyCollection over a private List

basics

~20 s

A backing field is the field EF Core reads and writes instead of the property, found by convention (_name) or named with HasField or [BackingField]. In the default PreferField mode EF bypasses getters and setters, so properties can be read-only or validated.

solid answer

~40 s

EF Core discovers a backing field by convention when a field is named after the property: `name`, `_name`, `_Name`, `m_name` or `m_Name`, in that order of precedence. Otherwise `HasField("_titleName")` or `[BackingField("_titleName")]` names it. The default `PropertyAccessMode.PreferField` makes EF read and write the field whenever one is known, so the public property can have no setter or a setter with validation that EF never triggers while loading rows. `UsePropertyAccessMode` changes that per property or model: `Field` forces field access, `Property` forces getters and setters, and the `...DuringConstruction` modes use the field only when materialising. The same mechanism lets a collection navigation be exposed as `IReadOnlyCollection<Review>` over a private `List<Review> _reviews`, with changes going through domain methods.

code

csharp · 17 lines
csharp
public class Title
{
    private string _titleName = "";

    [BackingField(nameof(_titleName))]
    public string Name
    {
        get => _titleName;
        set => _titleName = string.IsNullOrWhiteSpace(value)
            ? throw new ArgumentException("Name is required.")
            : value.Trim();
    }
}

// EF writes _titleName directly (PreferField): a blank legacy row still loads.
// To force the setter for EF as well:
// builder.Property(t => t.Name).UsePropertyAccessMode(PropertyAccessMode.Property);

go deeper

for a junior

Recall that EF Core can use a private field such as _name instead of the property, and that it finds such fields by naming convention.

for a middle

Explain HasField, [BackingField] and the PropertyAccessMode values, and why PreferField skips setter logic.

for a senior

Model encapsulated collections and validated properties so EF still loads imperfect legacy rows, and catch refactors that break convention-based field discovery.

for a principal

Weigh rich, encapsulated entities against simpler persistence models, and where EF's field access keeps or breaks domain invariants.

## Why backing fields exist Encapsulated entity classes keep invariants: a title name that cannot be blank, a review list only changed through `AddReview`. If EF Core had to go through public setters, every mapped property would need one, and every setter's validation would run while EF loads possibly imperfect legacy rows. **Backing fields** let EF read and write the **field** behind a property instead, while application code goes through the property and methods. ## How EF finds the field By convention, for a mapped property `Name`, EF looks for these fields, in this order of precedence: 1. `name` 2. `_name` 3. `_Name` 4. `m_name` 5. `m_Name` Fields are discovered only for properties that are part of the model. When the field name does not fit the pattern, name it explicitly: - fluent API: `builder.Property(t => t.Name).HasField("_titleName");` - attribute: `[BackingField(nameof(_titleName))]` on the property, from the `Microsoft.EntityFrameworkCore` namespace. ## What PropertyAccessMode controls The **`PropertyAccessMode`** enum decides whether EF uses the field or the property. The default is **`PreferField`**, and has been since EF Core 3.0. | Mode | Behaviour | |---|---| | `PreferField` (default) | Use the field when one is known, otherwise the property | | `Field` | Always use the field; throw if it cannot be read or written | | `FieldDuringConstruction` | Field only while materialising entities from a query; property otherwise | | `PreferFieldDuringConstruction` | Like the above, falling back to the property when no field is known | | `Property` | Always use the getter and setter; throw if one is missing | | `PreferProperty` | Use the property unless it lacks a getter or setter | Set it per property with `builder.Property(t => t.Name).UsePropertyAccessMode(PropertyAccessMode.Property)`, per navigation with `Navigation(...).UsePropertyAccessMode(...)`, or for the whole model with `modelBuilder.UsePropertyAccessMode(...)`. The practical consequence of the default: **setter logic does not run when EF loads or saves through the field**. A setter that trims or validates input protects application code paths, not rows coming back from the database. If the setter's side effect must run for EF too, switch that property to `Property` mode, and accept that loading a bad row now throws. ## Encapsulated collections The most common interview example is a collection navigation: ```csharp public class Title { private readonly List<Review> _reviews = []; public IReadOnlyCollection<Review> Reviews => _reviews; public void AddReview(Review review) { if (_reviews.Count >= 500) throw new InvalidOperationException("Too many reviews."); _reviews.Add(review); } } ``` EF discovers `_reviews` by convention and fills it when loading with `Include`, while callers cannot add to `Reviews` directly. If the field has another name, configure it with `builder.Navigation(t => t.Reviews).HasField("_reviewList")`. The relationship itself is configured like any other. ## Field-only properties A mapped value can also exist **only as a field**, with no property at all, for example an internal ISBN checksum. Configure it by name: `builder.Property<string>("_isbnCheck").HasColumnName("ISBN_CHK")`. EF looks for a CLR property with that name, then a field, and only if neither exists does it create a shadow property. In queries, reference it with `EF.Property<string>(t, "_isbnCheck")`. Unlike a shadow property, its value lives in the object, so it survives no-tracking queries. ## Choosing an access mode Most models never change the default, and that is usually right. Reasons to deviate: - **`Property`** for a property whose setter must run for EF as well, for example one that keeps two fields in sync. Loading a row that violates the setter's rule then throws, which may be what you want for data you control. - **`FieldDuringConstruction`** when loading should bypass validation but change tracking should still see writes made through the setter. - **`Field`** to make sure EF never touches a property's getter, for example one that computes or logs. Change the mode per property rather than for the whole model, so the exception stays visible where it matters. ## Pitfalls - **Assuming setter validation guards database data.** With `PreferField`, EF bypasses it. - **A get-only property with no discoverable field.** EF has nothing to write; add a conventional field, configure `HasField`, or keep the property out of the model. - **Changing a field name in a refactor.** Renaming `_reviews` to `reviewItems` breaks the convention match, so EF loses the field it was writing; name it with `HasField` after such a refactor and check the model again. - **Forcing `Property` mode model-wide** to make setters run, then hitting exceptions on every read-only property.

  • A legacy row has a blank title name and the Name setter throws on blanks. Does loading that row fail?
    Not with the default `PreferField` mode when EF knows the backing field: EF writes the field directly and never calls the setter, so the row loads. It would fail if the property were switched to `PropertyAccessMode.Property`, or if EF had no field and had to use the setter.
  • How does a backing field differ from a shadow property?
    A backing field stores the value in the object, so domain code inside the class can use it and it survives no-tracking queries. A shadow property has no member on the object at all; its value exists only in the change tracker entry. Both can be referenced in LINQ with `EF.Property<T>`.

  • EF Core always calls public setters when it loads an entity.
  • Every mapped property must have a public setter for EF Core to work.
  • The default PropertyAccessMode is Property, so setter validation guards loaded data.
  • A collection navigation must be a public List<T> with a setter.
  • A field named _name is never picked up unless HasField is called.