EF6 code: how to load DbCompiledModel from an EDMX file at startup?

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

Easy to write EDMX file for DbContext:

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

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

 var db = new DbContext(connectionString, myDbCompiledModel) 

However, there seems to be no way to read the EDMX file from disk in DbCompiledModel! How can i do this?

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

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

However, I do not want to use the version of the branch in the production environment. I tried to extract the EdmxReader utility from this branch, but it relies on the internal DbCompiledModel constructor, which I cannot access.

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

+8
entity-framework ef-code-first edmx
source share
1 answer

I tested if I can make it work by serializing the DbCompiledModel.

Both come from EF and provide it when creating a new context. The problem is that everything is closed, so it wonโ€™t serialize anything.

If you can get a serializer that you use to serialize private members, it should be pretty simple.

1) At the end of OnModelCreating (if you use the code first), you can do

 modelBuilder.Build().Compile() 

A bit simplified as you have to provide some arguments

2) Serialize it. To work with private members, try looking at JSON.Net: force serialize all private fields and all fields in subclasses or try using BinaryFormatter Why does BinaryFormatter serialize private elements, not XMLSerializer or SoapFormatter?

3) Save it to disk

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

+1
source share

All Articles