Query Types in EF Core 2.1
Posted: (EET/GMT+2)
Microsoft's preferred data access technology Entity Framework, or EF recently moved to version Core 2.1. This version introduced a feature called Query Types. This feature allows lightweight, read-only objects that let you map SQL queries or database views without requiring a primary key or change tracking.
To get started, define a simple class in C#:
public class OrderSummary
{
public int OrderId { get; set; }
public string Customer { get; set; }
public decimal Total { get; set; }
}
In your DbContext, register it with the Query<T> method:
public class SalesContext : DbContext
{
public DbQuery<OrderSummary> OrderSummaries { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Query<OrderSummary>()
.ToView("vwOrderSummary");
}
}
Then you can query it just like any other entity:
var summaries = context.OrderSummaries
.Where(o => o.Total > 1000)
.ToList();
Because Query Types are read-only, EF Core never tries to insert or update them. They are ideal for reports, joins, and projections where you don't need full change tracking.