我应该如何使用ContextProvider.EntityConnection创建辅助DbContext?

时间:2013-07-27 18:48:56

标签: entity-framework breeze

我正在使用Code First EF的微风。我的生产DbContext有IDatabaseInitializer,如果!context.Database.CompatibleWithModel(true)则抛出异常。如果我创建了像the documentation中建议的上下文,则无法检查数据库兼容性。

// 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

如何实例化提供ContextProvider的EntityConnection的DbContexts?

1 个答案:

答案 0 :(得分:1)

SaveChanges期间,Breeze的EFContextProvider使用默认构造函数创建DbContext实例。这发生在BeforeSaveEntity()BeforeSaveEntities()之前。因此,在创建第二个DbContext实例之前,您可以依赖第一个DbContext实例来检查兼容性。

在DbContext中,仅在默认构造函数中设置数据库初始值设定项。在采用DbConnection的构造函数中,将初始化程序设置为null:

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

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

这样,您可以在第二个DbContext上重新使用数据库连接,但仍然可以在第一个DbContext上使用初始化程序。

当然,您可以使用任何您想要的构造函数自由创建DbContexts,就像在Breeze 1.4之前一样。建议使用构造函数中的EntityConnection属性来帮助您保存数据库连接。