[C#][EF] dynamically change connection string in Entity Framework
前提: 我的資料庫名稱是MyScada 而EF的edmx模型命名為sqlScada
當使用Entity Framework (EF)由資料庫自動產生模型時
連線字串通常會被固定在App.config的<connectionStrings>中
想要依照使用者設定去做動態變更
可以使用以下方法
首先 更改 sqlScada.edmx/sqlScada.Context.tt/sqlScada.Context.cs
加入一個新的建構式
// default
public MyScadaEntities()
: base("name=MyScadaEntities")
{
}
// New
public MyScadaEntities(string nameOrConnectionString)
: base(nameOrConnectionString)
{
}
多載的建構式有了
接著就是如果產生新的連線字串
public string GetSQLConnectionString()
{
string DBName = "sqlScada";
SqlConnectionStringBuilder providerCs = new SqlConnectionStringBuilder();
providerCs.DataSource = "YourDBServerName";
providerCs.InitialCatalog = "YourDBName";
providerCs.IntegratedSecurity = false;
//providerCs.UserInstance = true;
providerCs.UserID = "YourDBUserID";
providerCs.Password = "YourDBPassword";
var csBuilder = new EntityConnectionStringBuilder();
csBuilder.Provider = "System.Data.SqlClient";
csBuilder.ProviderConnectionString = providerCs.ToString();
csBuilder.Metadata = string.Format("res://{0}/{1}.csdl|res://{0}/{1}.ssdl|res://{0}/{1}.msl",
typeof(MyScadaEntities).Assembly.FullName, DBName);
return csBuilder.ToString();
}
連線字串也有了 使用方法就很簡單了
public void UseNewDBConn()
{
MyScadaEntities myScada = new MyScadaEntities(GetSQLConnectionString());
// do whatever you want
}
新手發文,有謬誤請告知,也請多多指教。