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

1

9

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?

Crofton answered 7/1, 2015 at 10:2 Comment(0)
P
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

Praxiteles answered 14/8, 2015 at 9:16 Comment(2)
Brendan, Mikael was kind enough to test out the idea I emailed you about after I shared it with him. Let us know if this does the trick!Leanto
Mikael, thanks for responding to this question. I have tried serializing the DbCompiledModel using BinaryFormatter and JSON.Net with various settings but ran into self-referencing and non-[Serializable] issues. I have started a separate question with the details here. Can you shed any light and were you able to serialize it at all? #32110397Crofton

© 2022 - 2024 — McMap. All rights reserved.