连接字符串使用模型优先,数据库优先使用相同的数据库,

时间:2015-05-28 06:09:31

标签: c# asp.net

在Asp.net Entity框架中,我们同时使用Model First,DB同一数据库, 模型优先有两个连接字符串,DB优先。 那么我们如何为Model First,DB first创建单个连接字符串。

2 个答案:

答案 0 :(得分:0)

连接字符串将不同:数据库第一个将在开头具有元数据[嵌入]位置。你可以把"正常" Web.config中的Code First连接字符串,并添加"元数据部分"在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();
}

答案 1 :(得分:0)

您可以使用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
 );

编辑:

或者,您可以采用oposite方法,让我们保留EntityConnectionString并从中提取SqlConnectionString:

string entityConnectionString = 'xxxxxxx';
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder(entityConnectionString);

string sqlConnectionString = entityBuilder.ProviderConnectionString;