Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 748
Brendan Hill Avatar asked Jan 07 '15 10:01

Brendan Hill


1 Answers

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

like image 126
Mikael Eliasson Avatar answered Sep 19 '22 23:09

Mikael Eliasson