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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With