我已经创建了一个存储库类,并具有以下代码:
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="data source=server;initial catalog=Accident_Reporting;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" 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="data source=server;initial catalog=Accident_Reporting2;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
我想知道如何拥有多个连接并将Accident_Reporting__Entities
替换为另一个连接字符串。连接属于具有相同设计的不同数据库。是否可以检查会话变量并根据变量更改此连接,这是最好的方法吗?
答案 0 :(得分:2)
您可以将同一个DbContext与多个连接字符串一起使用:
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;");
或者您可以将Web.config文件中密钥的名称传递给构造函数:
<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");