Skip to content

Entity Framework Code First Model Cache

Sponsor: Using RabbitMQ or Azure Service Bus in your .NET systems? Well, you could just use their SDKs and roll your own serialization, routing, outbox, retries, and telemetry. I mean, seriously, how hard could it be?

Learn more about Software Architecture & Design.
Join thousands of developers getting weekly updates to increase your understanding of software architecture and design concepts.


With the release of Entity Framework 6.2, it introduces the Entity Framework Code First Model Cache.  Giving you the ability to load a prebuilt edmx when using code first, instead having EF generate it on startup. This can provide a some savings on startup time.
With these changes, first AppDomain calls to context.Database.Initialize for a model with just over 600 models and a null initializer dropped from 12-14 seconds to about 1.9 seconds after the edmx was written, saving 10-12 seconds on initialization. The first call to write the edmx still ran in 12-14 seconds (no noticeable delay added). #275
Now let’s be serious.  If you have 600 models in your DbContext, you have bigger problems than dealing with startup time.  But regardless, this should be beneficial even if you have a limited number of models.

DefaultDbModelStore

There is a DefaultDbModelStore which comes in the box that compares the timestamp between the assembly (dll) of your context against the edmx.  If they do not match, the edmx (cache) is deleted and rebuilt.

DbConfiguration

If you’re unaware of the DbConfiguration, take a look at the docs.  But the gist is to define the model store you want to use the in DbConfiguration using the new SetModelStore.
What this will do, is create the edmx files for your DbContext(s) in the direction where the application is executed.  Example while debugging the file generated would be be /bin/Debug/MyAssembly.MyNamespace.MyDbContext.edmx

Feedback

Love hearing your comments, please leave them bellow or on Twitter.