EF Core Backing Field — Complete Guide
In this tutorial, you'll learn about EF Core Backing Field. We cover key concepts, practical examples, and best practices.
Your entity has a property with logic in the getter or setter, or you want a read-only property that EF Core can still populate from the database. EF Core's backing field support lets you map a field instead of a property.
Wrong
public class Order
{
public decimal Total { get; set; } // Anyone can set it
}
// Some code accidentally sets Total incorrectly:
order.Total = 999; // No validation
Output: Total is publicly settable. Logic in the setter is bypassed.
Right
public class Order
{
private decimal _total; // Backing field
public decimal Total => _total; // Read-only property
public void SetTotal(IEnumerable<OrderItem> items)
{
_total = items.Sum(i => i.Price * i.Quantity);
}
}
// Mapping
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Order>()
.Property(o => o.Total)
.HasField("_total"); // Maps to backing field
}
Output: EF Core reads/writes the _total field directly. The public property is read-only. Business logic controls Total changes.
Backing fields also enable field-only properties:
private string _name; // No public property
// EF Core can still map it:
entity.Property<string>("_name").HasColumnName("Name");
Prevention
- Use
HasField()to map private fields for encapsulated properties. - Use
[Field("_fieldName")]data annotation as an alternative. - Use
UsePropertyAccessMode(PropertyAccessMode.Field)for field-only access. - Use backing fields with
INotifyPropertyChangedfor change tracking. - Use backing fields when the property does computation in getter/setter.
- Use backing fields for immutable types where only the field should be set during materialization.
Common Mistakes with core backing field
- Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
These mistakes appear frequently in real-world EF code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Backing fields are used in DodaTech's domain models for proper encapsulation. For more EF Core, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro