Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EntityFramwork, using multiple databases/connections

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.

like image 423
SirBirne Avatar asked Feb 09 '15 11:02

SirBirne


People also ask

Can we use multiple database in Entity Framework?

Multiple DbContext was first introduced in Entity Framework 6.0. Multiple context classes may belong to a single database or two different databases.


1 Answers

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...           
    }
}
like image 108
Pynt Avatar answered Sep 30 '22 19:09

Pynt