Does Entity Framework automatically cache the Mode

2019-04-05 02:02发布

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 ... ??

1条回答
可以哭但决不认输i
2楼-- · 2019-04-05 02:26

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

查看更多
登录 后发表回答