Search code examples
.net-coreentity-framework-coreedmx

How to cache Entity Framework Core model?


I have an Azure fabric cluster with .NET core 2.2 micro services inside of it. The mentioned services use EF core for communicating with Azure SQL databases. Also, the fabric cluster is behind a load balancer.

The database context has a scoped lifetime and is injected into the controllers using dependency injection.

Everything works well when the services are queried consistently by the same client, since the load balancer guarantees that for at least 4 minutes the same user will be sent to the same service instance. However, when the load balancer decides to send the user to a different instance, the database context is created again (since the lifetime is scoped, it means that a context is created per new web request). Unfortunately, the model building process takes quite long and due to that reason the first query is always way slower than the subsequent ones (on the same web request).

The questions would be, is it possible to somehow cache the EF Core model, so that it wouldn't have to be rebuilt every time the situation described above occurs ?

I mean, a similar procedure to EF - where an .edmx file is created once and loaded on context creation.


Solution

  • As of 3/3/2020 https://github.com/dotnet/efcore/issues/1906 this is still not possible.

    If you need model caching for performance reasons you will need to use EF 6. The good news is that EF 6.3 and the the SQL Server provider for EF 6 were ported over to run on .net core 3.0. However other providers may or may not port their code over so support may be spotty.

    https://devblogs.microsoft.com/dotnet/announcing-ef-core-3-0-and-ef-6-3-general-availability/#what-s-new-in-ef-6-3