EF Core Computed Column — Complete Guide
In this tutorial, you'll learn about EF Core Computed Column. We cover key concepts, practical examples, and best practices.
You calculate a FullName or TotalPrice in your application code every time you read an entity, repeating the same logic everywhere.
Wrong
public class Order
{
public decimal Subtotal { get; set; }
public decimal TaxRate { get; set; }
// Computed in application — repeated everywhere
public decimal Total => Subtotal * (1 + TaxRate);
}
Right
public class Order
{
public decimal Subtotal { get; set; }
public decimal TaxRate { get; set; }
public decimal Total { get; set; } // mapped to computed column
}
Configuration:
builder.Entity<Order>()
.Property(e => e.Total)
.HasComputedColumnSql("[Subtotal] * (1 + [TaxRate])", stored: true);
Stored (persisted) computed column:
builder.Entity<Order>()
.Property(e => e.Total)
.HasComputedColumnSql("Subtotal * (1 + TaxRate)", stored: true);
Prevention
- Use
HasComputedColumnSqlfor columns computed by the database. - Set
stored: truefor persisted columns (physically stored, indexed). - Set
stored: falsefor virtual computed columns (computed on read). - Computed columns can be used in indexes if persisted.
- The property is read-only from EF Core's perspective — EF won't try to insert/update it.
Common Mistakes with core computed column
- Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
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
Can I use computed columns in indexes?
Yes, if the computed column is persisted (`stored: true`). Virtual computed columns cannot be indexed.For more database patterns, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro