如何使用ContextProvider.EntityConnection创建辅助DbContext? [英] How should I create secondary DbContext using ContextProvider.EntityConnection?

查看:56
本文介绍了如何使用ContextProvider.EntityConnection创建辅助DbContext?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

创建一个DbContext应该如何实例化提供ContextProvider的EntityConnection的DbContext?

How should I instantiate DbContexts providing ContextProvider's EntityConnection?

推荐答案

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

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.

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

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);
}

这样,您可以在第二个DbContext上重新使用数据库连接,

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

自然地,您仍然可以使用所需的任何构造函数自由创建DbContext,就像在Breeze 1.4之前一样。建议在构造函数中使用 EntityConnection 属性,以帮助您节省数据库连接。

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.

这篇关于如何使用ContextProvider.EntityConnection创建辅助DbContext?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆