With one EDMX file use multiple connection strings that relate to multiple databases

拟墨画扇 提交于 2019-12-11 00:04:37

问题


I've got a program that has one .edmx file and in the app.config has three connection strings.

The schema that the .edmx represents is the same for 3 databases:

  1. Production
  2. Staging
  3. Development

and I want to make a method that basically does this (warning! Pseudo-code incoming)

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

Right now the code that I have is actually this, I don't see another method signature that accepts a connections string:

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

Is there a way to make my Entity Framework constructor in the using block take a connection string? I'm using EF 6.1 right now and I can't find a way.

Also if there is a better way to do this with Entity Framework I'm happy to switch my code around although using Entity Framework is a must.

If you need more code please let me know and I'll update with anything.


回答1:


When you create the EDMX you setup your context object for what it assumes will be a model with only one connection string. This is easily changed so you can have multiple connection strings with several duplicate databases.

When your model code is autogenerated you end up with a single connection DB Context. This is what this should look like in the source files...

-- MyModel.edmx
    -- MyModel.Context.tt
        -- MyModel.Context.cs

If you look in MyModel.Context.cs you should see this...

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

    ...
}

MyConnectionString corresponds to your connection string in your app config. Notice there is no constructor overload to use your own connection string but that's okay because we can leverage the partial class and the fact that DBContext does have an overload that takes a connection string.

Simply create another file in the same namespace as MyContext and use this code as a guide...

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

        ...
}

Done. Now you can use your context with any connection string

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

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


来源:https://stackoverflow.com/questions/24769451/with-one-edmx-file-use-multiple-connection-strings-that-relate-to-multiple-datab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!