EF6 code first: How to load DbCompiledModel from EDMX file on startup?

瘦欲@ 提交于 2019-12-06 22:49:50

问题


I want to reduce startup time in EF6 by caching the DbCompiledModel to disk.

It's easy to write the EDMX file for a DbContext:

EdmxWriter.WriteEdmx(myDbContext, XmlWriter.Create(@"C:\temp\blah.xml"))

And it's easy to pass a DbCompiledModel to the DbContext:

var db = new DbContext(connectionString, myDbCompiledModel)

However there doesn't seem to be any way to read the EDMX file from disk into a DbCompiledModel! How can I do this?

NOTE that I have successfully implemented the solution using the EdmxReader tool in this branched version of EF6:

https://github.com/davidroth/entityframework/tree/DbModelStore

However I am reluctant to use a branch version in a production environment. I have tried extracting the EdmxReader utility from this branch, but it relies on an internal constructor of DbCompiledModel which I can't access.

So, how can I get the EDMX file from disk and convert it into a DbCompiledModel?


回答1:


I tested if I could get it to work by serializing the DbCompiledModel.

Both getting it from EF and providing it when building a new context works. The problem is that everything is private so it will not serialize anything.

If you can get the serializer you use to serialize private members it should be quite simple.

1) In the end of OnModelCreating (if you are using code first) you can do

modelBuilder.Build().Compile()

Slightly simplified as you should provide some arguments

2) Serialize that one. For work with private members try looking at JSON.Net: Force serialization of all private fields and all fields in sub-classes or try to use the BinaryFormatter Why is the BinaryFormatter serializing private members and not the XMLSerializer or the SoapFormatter ?

3) Save that to disk

4) Read the file from disk and Deserialize it to a new DbCompiledModel



来源:https://stackoverflow.com/questions/27816842/ef6-code-first-how-to-load-dbcompiledmodel-from-edmx-file-on-startup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!