How should I create secondary DbContext using ContextProvider.EntityConnection?

别说谁变了你拦得住时间么 提交于 2019-11-28 10:50:43

问题


I'm using breeze with Code First EF. My production DbContext has IDatabaseInitializer that throws an exception if !context.Database.CompatibleWithModel(true). If I create a context like suggested in the documentation database compatibility cannot be checked.

// The following line will throw NotSupportedException.
// Unable to verify the compatibility of the model because
// the DbContext instance was not created using Code First patterns.
var context2 = new MyDbContext(EntityConnection, false);    // create a DbContext using the existing connection

How should I instantiate DbContexts providing ContextProvider's EntityConnection?


回答1:


During SaveChanges, Breeze's EFContextProvider creates a DbContext instance using the default constructor. This happens prior to BeforeSaveEntity() and BeforeSaveEntities(). So you can rely on that first DbContext instance to check compatibility before your second DbContext instance is created.

In your DbContext, set the database initializer only in the default constructor. In the constructor that takes a DbConnection, set the initializer to null:

public MyDbContext() : base()
{
    Database.SetInitializer(new CompatibilityCheckingInitializer<MyDbContext>);
}

public MyDbContext(DbConnection connection) : base(connection, false)
{
    Database.SetInitializer(null);
}

This way, you can re-use the database connection on your second DbContext, but still have the initializer working on your first.

Naturally, you are still free to create DbContexts using any constructor you want, as you would have prior to Breeze 1.4. Using the EntityConnection property in your constructor is suggested as a way to help you conserve database connections.



来源:https://stackoverflow.com/questions/17901261/how-should-i-create-secondary-dbcontext-using-contextprovider-entityconnection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!