使用一个EDMX文件,使用与多个数据库相关的多个连接字符串

Jos*_*h R 2 c# entity-framework edmx

我有一个程序有一个.edmx文件,在app.config中有三个连接字符串.

.edmx表示的模式对于3个数据库是相同的:

  1. 生产
  2. 分期
  3. 发展

我想制作一个基本上做到这一点的方法(警告!伪代码传入)

foreach(var connectionString in connectionStrings) {
    using (MyCustomDBEntities context = new MyCustomDBEntities(connectionString)) {
        // Do cool things, like insert new records, update records, etc...
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我的代码实际上就是这个,我没有看到另一个接受连接字符串的方法签名:

foreach(var connectionString in connectionStrings) {
    using (MyCustomDBEntities context = new MyCustomDBEntities()) {
        // Do cool things, like insert new records, update records, etc...
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法让我的实体框架构造函数在using块中使用连接字符串?我现在正在使用EF 6.1,我找不到办法.

此外,如果有更好的方法使用Entity Framework执行此操作,我很乐意切换我的代码,尽管使用Entity Framework是必须的.

如果您需要更多代码,请告诉我,我会更新任何内容.

Sho*_*hoe 5

在创建EDMX时,您可以设置上下文对象,假设它只是一个连接字符串的模型.这很容易更改,因此您可以拥有多个具有多个重复数据库的连接字符串.

当您的模型代码自动生成时,您最终会得到一个连接数据库上下文.这就是源文件中应该是这样的......

-- MyModel.edmx
    -- MyModel.Context.tt
        -- MyModel.Context.cs
Run Code Online (Sandbox Code Playgroud)

如果你看,MyModel.Context.cs你应该看到这个......

public partial class MyContext : DbContext
{
    public MyContext ()
        : base("name=MyConnectionString")
    {
    }

    ...
}
Run Code Online (Sandbox Code Playgroud)

MyConnectionString对应于应用配置中的连接字符串.请注意,没有构造函数重载来使用您自己的连接字符串,但这没关系,因为我们可以利用具有连接字符串的重载partial class的事实DBContext.

只需在同一名称空间中创建另一个文件,MyContext并使用此代码作为指南...

public partial class MyContext : DbContext
{
        public MyContext (string nameOrConnectionString)
            : base(nameOrConnectionString)
        {
        }

        ...
}
Run Code Online (Sandbox Code Playgroud)

完成.现在,您可以将您的上下文用于任何连接字符串

using(var context = new MyContext(connectionstring1))
{
    ...
}

using(var context = new MyContext(connectionstring2))
{
    ...
}
Run Code Online (Sandbox Code Playgroud)