摘要:Entity 自行指定連線字串
如果要跨多db而且同table需求的話,這方式就用得到了,因為我用的是mvc,所以如果有別種專案的,就自行想像囉
我是先在model裡面建立一個類別
public static class ConnString
{
public static EntityConnectionStringBuilder GetConnection()
{
var sqlBuilder = new SqlConnectionStringBuilder();
sqlBuilder.DataSource = "server的ip";
sqlBuilder.InitialCatalog = "指定的db";
sqlBuilder.IntegratedSecurity = false;
sqlBuilder.UserID = "登入帳號";
sqlBuilder.Password = "密碼";
var entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.ProviderConnectionString = sqlBuilder.ToString();
entityBuilder.Provider = "System.Data.SqlClient";
entityBuilder.Metadata = "res://*/Models.Model1.csdl|res://*/Models.Model1.ssdl|res://*/Models.Model1.msl";
return entityBuilder;
}
}
接著去model.edmx底下有model.Context.cs
改成這樣子,指定建構值進去
public CooperEntities(string ConnString)
: base(ConnString)
{
}
接著就是去controller下語法。
private CooperEntities db;
public DoctorApiController()
{
var conn = ConnString.GetConnection(); //這邊就是我上面自行指定的類別,為了得到指定的ip字串,要活用的話就自行變換囉。
db = new CooperEntities(conn.ToString());
}