简体   繁体   English

如何在项目中使用多个实体框架连接字符串?

[英]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: 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. 我想知道如何拥有多个连接并将Accident_Reporting__Entities替换为另一个连接字符串。 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: 您可以将相同的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;");

Or you can pass to the contructor the name of the key in the Web.config file: 或者,您可以将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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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