简体   繁体   中英

EF Code-first: how to cache DbCompiledModel?

I have setup a simple test project for the EF 4.1 RC, using Code-First aproach. What I see, that every call to new MyContext() is taking quite a long time. I found, that there is a constructor which accept DbCompiledModel and the description http://msdn.microsoft.com/en-us/library/system.data.entity.infrastructure.dbcompiledmodel(v=VS.103).aspx says, that it is good to cache this object, for better performance. But I can`t find how to get the DbCompiledModel from existing context. And there are no samples on the net.

Model is already cached. You can validate it easily by placing breakpoing to your OnModelCreating method. It will be hit only first time you create context. If you want to create DbCompiledModel manually you must first create DbModelBuilder outside of your context. Use its Build method and then Compile resulting DbModel .

Here`s what I found after rethinking. You can get yourself a copy of compiled model with the following code.

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        var model = modelBuilder.Build(Database.Connection);
        var compliedModel = model.Compile();
    }

But, when I passed that model to my context and made some performance tests, and compared them with a plain call to new MyContext(). I found, that context is already caching the compiled model, since the times were identical. So, caching of compiled model, seems to only needed, when it is handcrafted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM