如何从两个连接字符串中进行选择?

时间:2011-12-24 15:27:51

标签: c# asp.net linq-to-entities

下午好,我遇到了使用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。如何允许管理员使用第一个连接字符串登录,而职员将使用第二个连接字符串登录?

enter image description here

2 个答案:

答案 0 :(得分:5)

改编自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。

答案 1 :(得分:2)

var conn = new EntityConnection();
conn.StoreConnection.ConnectionString = ConfigurationManager.ConnectionStrings["GameHutDBEntities2"];

this.Entities = new KurtDBEntities(conn);