Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Entity Framework automatically cache the ModelBuilder model?

I am developing an ASP MVC application using Entity Framework. I was thinking of writing code to cache the object returned by ModelBuilder (as is recommended by several sources), but then I ran into this on Scott Gu's blog:

"The OnModelCreating method above will be called the first time our NerdDinners class is used within a running application, and it is passed a “ModelBuilder” object as an argument. The ModelBuilder object can be used to customize the database persistence mapping rules of our model objects. We’ll look at some examples of how to do this below.

"EF only calls the “OnModelCreating” method once within a running application – and then automatically caches the ModelBuilder results. This avoids the performance hit of model creation each time a NerdDinners class is instantiated, and means that you don’t have to write any custom caching logic to get great performance within your applications."

Does this mean that EF automatically caches the ModelBuilder object, and I don't have to write code to do it, or is this something that is only done if the OnModelCreating method is overridden, or ... ??

like image 854
Cynthia Avatar asked Aug 31 '10 17:08

Cynthia


People also ask

Does Entity Framework cache results?

Entity Framework has the following forms of caching built-in: Object caching – the ObjectStateManager built into an ObjectContext instance keeps track in memory of the objects that have been retrieved using that instance. This is also known as first-level cache.

Does Entity Framework cache queries?

The first time a query is invoked, data is retrieved from the database and stored in memory before being returned. The compiled queries could be cached for the life of an app pool instance and provided to the Entity Framework for low latency performance of data access.

Does Entity Framework core cache?

Entity Framework Core does not come with its caching framework (like NHibernate does). However, NCache has developed a very flexible, powerful, and yet very simple caching framework for you.

Does EF core cache data by default?

The Cache: The memory cache is used by default.


1 Answers

From the Entity Framework Blog regarding performance improvements in EF 4

Model Caching

There is some cost involved in discovering the model, processing Data Annotations and applying fluent API configuration. To avoid incurring this cost every time a derived DbContext is instantiated the model is cached during the first initialization. The cached model is then re-used each time the same derived context is constructed in the same AppDomain. Model caching can be turned off by setting the CacheForContextType property on ModelBuilder to ‘false’ in the OnModelCreating method.

So the answer is yes for Entity Framework 4.0

like image 86
Josh Avatar answered Sep 20 '22 08:09

Josh