I have the following Problem. I'm using Entity Framework 6 and i want to be able to change the used database on runtime or atleast I want to be able to check connection information when entered in the Options. My problem is that we want to support MySql and LocalDB v12.0 so simple exchanging the connections string doesn't help here - I have to exchange the ExecutionStrategy and the ConnectionFactory.
EF seems to lock down all configurations so I'm not able to change it on runtime, is there a workarround for this? For the moment I've tried to create several DbConfigurations and derive a context for each configuration with a definition of [DbConfigurationType(typeof(LocalDbConfigruation))]
.
I expected this to fail, but i thougt it would be worth a try ;)
Maybe there is someone out there who can help me with some tipps and tricks.
Multiple DbContext was first introduced in Entity Framework 6.0. Multiple context classes may belong to a single database or two different databases.
There is another option that utilizes a base context. In the below example I am using MSSQL connection and Oracle connection. You can extend the base context for however many database connection types you wish. This method opens a ton of other great possibilities, but it should also work for your situation.
BaseContext.cs
using System.Data.Entity;
namespace MultipleConnections.Models
{
public class BaseContext<TContext> : DbContext where TContext : DbContext
{
static BaseContext()
{
Database.SetInitializer<TContext>(null);
}
public BaseContext(string connectionString = "Name=MSSQLEntities")
: base(connectionString)
{}
}
}
MSSQLModel.cs
using System.Data.Entity;
namespace MultipleConnections.Models
{
// Extending Base Context will use default MSSQLEntities connection
public class MSSQLContext : BaseContext<MSSQLContext>
{
...apply DbSet<> and other loveliness...
}
}
OracleModel.cs
using System.Data.Entity;
namespace MultipleConnections.Models
{
// Extending Base Context
public class OracleContext : BaseContext<OracleContext>
{
// Declare Oracle connection in Constructor to override default
// MSSQL connection
public OracleContext()
: base("Name=OracleEntities")
{ }
...apply DbSet<> and other loveliness...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With