我不喜欢将整个实体框架连接字符串存储在任何.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))