Wednesday, September 4, 2019

Entity Framework Core Query Objects

Although the name suggests otherwise you are not limited to using entity types (=objects with an id) in EF Core. EF Core 2.1 introduces support for query types, which can be used to query data that isn’t mapped to entity types.

This allows you to directly map your query results to DTO’s, something especially useful on the query side when you are having a CQRS style architecture.

Let’s try this!

First we have to create our DTO:

Next step is to make EF Core aware of the existence of this query type. We’ll use the fluent configuration api but instead of calling the Entity<T>() method on the modelBuilder we’ll use the Query<T>() method:

Next, we configure the DbContext to include the DbQuery<T>:

You can then define queries directly in OnModelBuilding using a LINQ query through ToQuery():

Of course you can also map a query type to a view using ToView():

A last option is to directly map it to a raw SQL query using the FromSql method on your DbContext:

Remark: The query type must be registered with the DbContext as a DbQuery and all columns in the SQL need to match all of the properties in the query type.

More information: