2013-07-27 47 views
1

我使用Code First EF使用breeze。我的产品DbContext有IDatabaseInitializer,如果!context.Database.CompatibleWithModel(true)引发异常。如果我创建了如the documentation中建议的上下文,则无法检查数据库兼容性。如何使用ContextProvider.EntityConnection创建辅助DbContext?

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

+0

不,事实并非如此。 MyDbContext使用Code First构建模型。一切工作正常,当我创建它只传递连接字符串或使用默认的ctr。 'var context2 = new MyDbContext();' – pawel

+0

DOCU中的部分创建ObjectContext/DbContext动态? –

+0

@ phil-soady按照我提供的链接向下滚动到“用于BeforeSaveEntities和AfterSaveEntities的ContextProvider方法”http://www.breezejs.com/documentation/custom-efcontextprovider#ContextProvidermethods。 – pawel

回答

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数据库连接,但仍然有初始化你的第一个工作。

当然,你仍然可以使用任何你想要的构造函数来创建DbContexts,就像你之前的Breeze 1.4一样。建议在构造函数中使用EntityConnection属性作为帮助您节省数据库连接的一种方法。

+0

这是有道理的,以检查第一个DbContext的兼容性。目前还不清楚为什么第二个DbContext认为它不是Code First? – pawel

+1

我认为这是因为EntityConnection(我们在DbContext构造函数中传递的)已经有与其关联的元数据,所以它不需要像Code First一样通常构建元数据。我们不能给它一个普通的DbConnection,因为[EntityConnection只能用封闭的DbConnection构造](http://blogs.msdn.com/b/diego/archive/2012/01/26/exception-from-dbcontext -API-entityconnection-可以仅待构造上带有一个封闭-dbconnection.aspx) –

相关问题