Entity Framework DefaultConnectionFactory being ig

2019-02-15 12:04发布

问题:

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)
{

}