下午好,我遇到了一个问题,无法使用C#和Linq to Entities从两个连接字符串中进行选择。目前,我有两个连接字符串:

<add name="GameHutDBEntities1" connectionString="metadata=res://*/GameHutModel.csdl|res://*/GameHutModel.ssdl|res://*/GameHutModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=EMMANUEL-PC\SQLEXPRESS;Initial Catalog=GameHutDB;user id=GameHutAdmin; password=123;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />
<add name="GameHutDBEntities2" connectionString="metadata=res://*/GameHutModel.csdl|res://*/GameHutModel.ssdl|res://*/GameHutModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=EMMANUEL-PC\SQLEXPRESS;Initial Catalog=GameHutDB;user id=test; password=1234;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />


我有两个角色,分别是Admin和Clerk。如何允许管理员使用第一个连接字符串登录,而业务员将使用第二个连接字符串登录?

最佳答案

改编自this answer

string connString;

if(IsAdmin(user))
    connString = ConfigurationManager.ConnectionStrings["GameHutDBEntities1"];
else
    connString = ConfigurationManager.ConnectionStrings["GameHutDBEntities2"];

using(EntityConnection con = new EntityConnection(connString))
{
  using (Entities context = new Entities(con))
  {
      // Some code here
  }
}


其中IsAdmin是采用user的函数,如果他是管理员则返回true,否则返回false。

10-04 14:49