连接字符串使用模型优先,数据库优先为同一数据库,
本文关键字:数据库 字符串 连接 模型 | 更新日期: 2023-09-27 17:50:55
在Asp.net Entity框架中,我们对同一个数据库使用Model优先,DB优先,有两个连接字符串模型第一,数据库第一。那么我们如何为模型优先,数据库优先创建单个连接字符串呢?
您可以使用EntityConnectionStringBuilder:
string sqlConnectionString = "Data Source=localhost;
Initial Catalog=AdventureWorks;Integrated Security=True;Connection Timeout=60;multipleactiveresultsets=true"
string providerName = "System.Data.SqlClient";
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.Provider = providerName;
entityBuilder.ProviderConnectionString = sqlConnectionString;
entityBuilder.Metadata = @"res://*/AdventureWorksModel.csdl|
res://*/AdventureWorksModel.ssdl|
res://*/AdventureWorksModel.msl";
string entityConnectionString = entityBuilder.ToString();
或者,如果你足够勇敢,你可以尝试重新格式化entityConnectionString:
string sqlConnectionString = "Data Source=localhost;
Initial Catalog=AdventureWorks;Integrated Security=True;Connection Timeout=60;
multipleactiveresultsets=true"
string entityConnectionString =
string.Format("metadata=.'AdventureWorks.csdl|.'AdventureWorks.ssdl|.'AdventureWorks.msl; provider=System.Data.SqlClient;provider connection string='{0}'" providerName='"System.Data.EntityClient'"",
sqlConnectionString
);
编辑:或者,您可以采取相反的方法,让我们保留EntityConnectionString并从中提取SqlConnectionString:
string entityConnectionString = 'xxxxxxx';
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder(entityConnectionString);
string sqlConnectionString = entityBuilder.ProviderConnectionString;
连接字符串将是不同的:DB第一个将在开始时具有元数据[嵌入]位置。你可以把"普通的"Code First连接字符串放到web上。配置并在DB First DbContext构造函数中添加"元数据部分",使用静态方法构建所需的EntityConnectionString。
的例子:
public MyContext() : base(BuildConnectionString())
{
}
private static string BuildConnectionString()
{
varsqlBuilder = new SqlConnectionStringBuilder();
//dinamically prepare the provider connection string here, using the CF one in the web.config
//[..]
//now build the entity connection string, using the one just built as ProviderConnectionString
var entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.ProviderConnectionString = sqlBuilder.ToString();
entityBuilder.Metadata = "res://*/";
entityBuilder.Provider = "System.Data.SqlClient";
return entityBuilder.ToString();
}