私はエンティティ フレームワークの接続文字列全体を任意.config
のファイルに保存するのが好きではありません。そこで代わりに、標準文字列を有効なエンティティ フレームワーク接続文字列に変換するメソッドを作成しました。
private static string GetEntityConnectionString(string connectionString,
Type contextType)
{
string result = string.Empty;
string prefix = contextType.Namespace
.Replace(contextType.Assembly
.GetName()
.Name,
string.Empty);
if (prefix.Length > 0
&& prefix.StartsWith("."))
{
prefix = prefix.Substring(1, prefix.Length - 1);
}
if (prefix.Length > 1
&& !prefix.EndsWith("."))
{
prefix += ".";
}
EntityConnectionStringBuilder csBuilder
= new EntityConnectionStringBuilder();
csBuilder.Provider = "System.Data.SqlClient";
csBuilder.ProviderConnectionString = connectionString.ToString();
csBuilder.Metadata = string.Format("res://{0}/{1}.csdl|"
+ "res://{0}/{1}.ssdl|"
+ "res://{0}/{1}.msl",
contextType.Assembly.FullName,
prefix + contextType.Name);
result = csBuilder.ToString();
return result;
}
これで、構成ファイルに適切な接続文字列が得られます。
<add name="MyDbConnectionname"
connectionString="Data Source=localhost\sqlexpress;Integrated Security=SSPI;MultipleActiveResultSets=true"
providerName="System.Data.SqlClient" />
そして、あなたはそれを次のように呼びます:
var db = new DbContext(
DbContext.GetEntityConnectionString(connectionString,
typeof(DbContext))