Entity Framework: multiple DB having the same schema

与世无争的帅哥 提交于 2019-12-23 03:26:18

问题


I have just created an ASP.NET MVC 4 & WebAPI project. After that I have added .edmx data source to project.

I have multiple databases with the same schema. Dynamically I want to replace connection string using default constructor provided in EF.

But in Model1.Designer.cs, every time I get error like "Member with same signature already declared".

I'm unable to solve this problem.


回答1:


Yes, it works! All you need to change is the connection string.

And I have just tested it in order to satisfy my own curiosity.

Here are the steps that I took:
1. Take an existing database and create a model for it.
2. Create a new empty database.
3. In SQL Management Studio right click the first database -> Tasks -> Export Data. Export all it's data to the newly created database.
4. Remove some records from the second database.
5. Write this code:

    TMS_MiscEntities db = new TMS_MiscEntities();
    TMS_MiscEntities dbCopy = new TMS_MiscEntities();
    dbCopy.Database.Connection.ConnectionString = db.Database.Connection.ConnectionString.Replace("initial catalog=TMS_Misc", "initial catalog=TMS_Misc_new");

    Response.Write(string.Format("DB 1 records: {0}<br/>", db.ZipCodes.Count()));
    Response.Write(string.Format("DB 2 records: {0}<br/>", dbCopy.ZipCodes.Count()));

6. Check results:

DB 1 records: 869164
DB 2 records: 868709

7. Conclude that it works :)

This is how my connection string looks:

<add name="TMS_MiscEntities" connectionString="metadata=res://*/DbModel.csdl|res://*/DbModel.ssdl|res://*/DbModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=ws2008;initial catalog=TMS_Misc;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />



回答2:


I'm using Entity Framework 6.1.3. I have added a constructor to my DbContext that takes a string parameter. This string can be the name of the connection stored in your App.config or a full connection string. Something like this:

public partial class MyDBContext : DbContext
{
    public MyDBContext(string connectionString)
        : base(connectionString)
    {
    }

   // DbSets, OnModelCreating, etc 
}

In my case, I manage a multi-tenant application and I use a ContextFactory to build the proper connection string and return my initialized context.

public class ContextFactory
{
    public MyDbContext GetContext()
    {
        string connectionString;
        // do some stuff here
        return new MyDbContext(connectionString);
    }
}


来源:https://stackoverflow.com/questions/27249579/entity-framework-multiple-db-having-the-same-schema

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