实体框架DefaultConnectionFactory被忽略 [英] Entity Framework DefaultConnectionFactory being ignored

查看:93
本文介绍了实体框架DefaultConnectionFactory被忽略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用具有代码优先级的实体框架5。我已经编写了一个自定义的 IDbConnectionFactory ,我想用于我的 DbContext 类的所有连接,所以早在应用程序的生命周期中,在任何数据库工作完成之前,我调用

  Database.DefaultConnectionFactory = new MyConnectionFactory(); 

然而, MyConnectionFactory.CreateConnection 永远不会被调用,这向我建议,EF改变了它 - 但调试器显示,它仍然是一个 MyConnectionFactory ,几个查询运行后。由于某种原因,它只是不使用它。



我的 DbContext 通过传递连接字符串的名称进行初始化从app.config文件,这些连接字符串确实指定一个显式提供程序(确实他们必须),所以我想知道是否导致基于连接字符串连接工厂的每连接覆盖。这是否发生,我可以停止它,而不注册一个全新的提供商(虽然也许这不是太难做吗?)。



无论我在网上看到什么(很模糊通过各种app.config示例中的defaultConnectionFactory标签)建议您只需将其更改为您选择的 IDbConnectionFactory 实例,它将工作,但我的行为不正常。



这样做的目的是允许我在打开一个新的连接时运行一组特定的SQL语句,所以这个问题的第二部分是有人知道的

解决方案

我知道这不太理想,但这对我有用:

  public class DBBase:DbContext 
{
public DBBase(string nameOrConnectionString)
:base(Database.DefaultConnectionFactory.CreateConnection (nameOrConnectionString),true)
{
}
// ...
}


I'm using Entity Framework 5 with Code First. I've written a custom IDbConnectionFactory which I want to use for all the connections made by my DbContext class, so early on in the application's lifecycle, before any database work is done, I call

Database.DefaultConnectionFactory = new MyConnectionFactory();

However, MyConnectionFactory.CreateConnection is never called, which suggests to me that EF's changed it back - but the debugger shows that it's still a MyConnectionFactory after several queries have run. For some reason, it's just not using it.

My DbContext is initialised by passing the name of a connection string from the app.config file, and those connection strings do specify an explicit provider (as indeed they have to) so I'm wondering if that's causing a per-connection override of the connection factory based on the connection string. Does this happen and can I stop it without registering a completely new provider (although maybe that's not too hard to do?).

Whatever I see online about this (much obscured by the defaultConnectionFactory tag in various app.config examples) suggests you can just change it to an IDbConnectionFactory instance of your choice and it'll work, but mine isn't behaving.

The purpose of this is to allow me to run a particular set of SQL statements whenever a new connection is opened, so the second part of this question would be does anybody know a better way to do this?

解决方案

I know it is not ideal but this worked for me:

public class DBBase : DbContext
{
    public DBBase(string nameOrConnectionString)
        : base(Database.DefaultConnectionFactory.CreateConnection(nameOrConnectionString), true)
    {
    }
    // ...
}

这篇关于实体框架DefaultConnectionFactory被忽略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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