What is EF Core Projectables?
masterEF Core Projectables is a library that allows you to define reusable business logic (properties, methods, or constructors) directly on your entities using the [Projectable] attribute. These members are automatically translated into efficient SQL by a source generator, allowing you to use them in LINQ queries (Where, OrderBy, Select, etc.) without manual expression tree boilerplate or client-side evaluation.
Key benefits include:
- Write Once, Use Anywhere: Define a complex calculation once and use it in any LINQ query.
- Composable Logic: Projectable members can call other projectable members.
- SQL Translation: Supports pattern matching (switch expressions), null-conditional operators (
?.), and enum method expansion, all rewritten into SQLCASEexpressions. - Provider Agnostic: Works with any EF Core provider (SQL Server, PostgreSQL, SQLite, Cosmos DB, etc.).
class Order
{
public decimal TaxRate { get; set; }
public ICollection<OrderLine> Lines { get; set; }
[Projectable]
public decimal Subtotal => Lines.Sum(l => l.Quantity * l.UnitPrice);
[Projectable]
public decimal Total => Subtotal * (1 + TaxRate);
[Projectable]
public string Tier => Subtotal switch
{
> 1000 => "Premium",
> 250 => "Standard",
_ => "Basic"
};
}
// Usage in LINQ
var orders = dbContext.Orders
.Where(o => o.Subtotal > 500)
.OrderByDescending(o => o.Total)
.Select(o => new { o.Total, o.Tier })
.ToList();