Entity Framework DefaultConnectionFactory being ignored
ef-code-first, entity-framework, entity-framework-5
Solution
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)
{
}
// ...
}
Problem
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?