Entity Framework DefaultConnectionFactory being ignored

一个人想着一个人 提交于 2019-11-30 20:26:36

问题


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?


回答1:


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)
    {
    }
    // ...
}



回答2:


You need to get the connection that you built for each call that you are wanting to use. For example using the following code.

private static void UsingCustomConnection()
{
    using (var conn = Database.DefaultConnectionFactory.CreateConnection("YourDbName"))
    {
        using (var context = new YourContext(conn))
        {
            context.Destinations.Add(new Destination {Name = "Colorado"});
            context.SaveChanges();
        }
    }
}

You will need to setup this in YourContext

public YourContext(DbConnection connection)
    : base(connection, contextOwnsConnection: false)
{

}


来源:https://stackoverflow.com/questions/13724807/entity-framework-defaultconnectionfactory-being-ignored

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