实体框架,使用多个 databases/connections

EntityFramwork, using multiple databases/connections

我有以下问题。我正在使用 Entity Framework 6,我希望能够在运行时更改使用的数据库,或者至少我希望能够在选项中输入时检查连接信息。我的问题是我们想要支持 MySql 和 LocalDB v12.0,所以简单地交换连接字符串在这里没有帮助——我必须交换 ExecutionStrategy 和 ConnectionFactory。

EF 似乎锁定了所有配置,因此我无法在运行时更改它,是否有解决方法?目前,我尝试创建多个 DbConfigurations 并为每个配置派生上下文,定义为 [DbConfigurationType(typeof(LocalDbConfigruation))].

我预计这会失败,但我认为值得一试 ;)

也许有人可以帮我一些小窍门。

好的,问题似乎已经解决了。我现在正在使用 DbConnections。

public MyContext() : base(ConnectionManager.Connection, true)
{
    Database.SetInitializer<MyContext>(new MyContextInitializer());
    Configuration.ProxyCreationEnabled = false;
}

public MyContext(DbConnection connection) : base(connection, true)
{
    Database.SetInitializer<MyContext>(new MyContextInitializer());
    Configuration.ProxyCreationEnabled = false;
}

我在一个特殊的 class 中创建了 DbConnection,我认为 post 这里的代码不合适。但它基本上是这样做的:

DbConnection conn = null;

switch (Type)
{
   case ConnectionType.LocalDB:
      conn = DbProviderFactories.GetFactory("System.Data.SqlClient").CreateConnection();
      break;
   case ConnectionType.MySql:
      conn = DbProviderFactories.GetFactory("MySql.Data.MySqlClient").CreateConnection();
      break;
   default:
      throw new System.InvalidOperationException();
}

conn.ConnectionString = "Add provider specific connection string here";

然后你只需要将代码以某种方式提供给上下文。在我的例子中,我有一个 ConnectionManager,当我调用 MyContext() 时,我从那里读取 "defaul connection" 并且有第二个 Ctor,我调用它 "test connections".

还有另一个选项使用基本上下文。 在下面的示例中,我使用了 MSSQL 连接和 Oracle 连接。 您可以根据需要为任意多种数据库连接类型扩展基本上下文。这种方法打开了大量其他的可能性,但它也应该适用于您的情况。

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...           
    }
}