简体   繁体   中英

How can I use multiple entity framework connection strings in a project?

I've created a repository class and have the following code:

public class InventoryDA : Accident_Reporting_Entities
{

}

Web.config:

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

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

I'm wondering how I can have multiple connections and replace Accident_Reporting__Entities with another connection string. The connections are of different databases that have the same design. Is it possible to check for a session variable and change this connection according to the variable, and would this be the best way?

You can use the same DbContext with multiple connection strings:

public partial class SchoolDBEntities : DbContext
{
    public SchoolDBEntities(string connectionString) : base(connectionString)
    {

    }
}

var db1 = new SchoolDBEntities("Server=myServerAddress;Database=myDataBase1;User Id=myUsername;Password=myPassword;");
var db2 = new SchoolDBEntities("Server=myServerAddress;Database=myDataBase2;User Id=myUsername;Password=myPassword;");

Or you can pass to the contructor the name of the key in the Web.config file:

<configuration>
    <connectionStrings>
        <add name="myDataBase1" connectionString="Server=myServerAddress;Database=myDataBase1;User Id=myUsername;Password=myPassword;" />
        <add name="myDataBase2" connectionString="Server=myServerAddress;Database=myDataBase2;User Id=myUsername;Password=myPassword;" />
    </connectionStrings>
</configuration>

var db1 = new SchoolDBEntities("myDataBase1");
var db2 = new SchoolDBEntities("myDataBase2");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM