Entity Framework Core 2 – Explicit compiled queries

 

Entity Framework Core 2 was released on August 14th. It brought new features.

On this article I will explain one of them: Explicitly compiled queries

Entity Framework Core included query caching since version 1, but there is still some overhead associated with calculating the key from the query and getting it from the cache. Therefore, version 2 introduced a capability that existed in LINQ to SQL and Entity Framework 5: explicit query compilation and execution. By this, we are able to pre-compile a query and use it in whatever context we want (of a compatible type, of course). We can even eagerly fetch associated collections or entities.

Example:

private static Func<AdventureWorksContextDI, int, Orders> _getOrderById =
  EF.CompileQuery((AdventureWorksContextDI context, int id) =>
  context.WorkOrders.Select(
  x => new Orders
  {
     Id = x.WorkOrderId,
     ProductName = x.Product.Name,
     Quantity = x.OrderQty,
     Date = x.DueDate
  }).FirstOrDefault(x => x.Id == id));

Usage:

public Orders GetOrderByIdCompiled(int id)
{
   return _getOrderById(_context, id);
}

What performance improvments to expect ?

I executed the non compiled query and the same version but compiled (using Stopwatch object), and I measured this:

  • Compiled query: 2 to 15 ms
  • Non compiled query: 4 to 23 ms

 

It looks faster 🙂