2

让我们考虑列出的实体类

public NerdDinnerEntities() : base("name=NerdDinnerEntities", "NerdDinnerEntities")
        {

            this.ContextOptions.LazyLoadingEnabled = true;

            OnContextCreated();
        }

        /// <summary>
        /// Initialize a new NerdDinnerEntities object.
        /// </summary>
        public NerdDinnerEntities(string connectionString) : base(connectionString, "NerdDinnerEntities")
        {
            this.ContextOptions.LazyLoadingEnabled = true;

            OnContextCreated();
        }



        /// <summary>
        /// Initialize a new NerdDinnerEntities object.
        /// </summary>
        public NerdDinnerEntities(EntityConnection connection) : base(connection, "NerdDinnerEntities")
        {
            this.ContextOptions.LazyLoadingEnabled = true;
            OnContextCreated();
        }  

这些在 web 配置文件中被读取为

<add name="NerdDinnerEntities" 
    connectionString="metadata=res://*/Models.NerdDinner.csdl|res://*/Models.NerdDinner.ssdl|res://*/Models.NerdDinner.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=*;
    Initial Catalog=db;User ID=*;Password=****;
    MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />

我的问题是我需要通过代码将数据库名称从 db 更改为 db1 而无需更改 web 配置文件..

作为一个名为changedatabase()的类名的实体......但我不知道如何使用它......

我的另一个问题是可以在这个项目中添加一个新的 dll 并在那里更改连接字符串元数据,只要在那里打开连接,它就会到达该 dll 并仅更改数据库名称并返回该数据库。 ..

等待您宝贵的命令和建议

4

1 回答 1

1
public class MyEntities : NerdDinnerEntities
{
  public MyEntities() : base(GetConnectionString())
  {
  }

  private string GetConnectionString()
  {
    var connectionString = System.Configuration.ConfigurationManager.
        ConnectionStrings["connectionStringName"].ConnectionString;
    var builder = new System.Data.Common.DbConnectionStringBuilder();
    builder.ConnectionString = connectionString;
    var internalConnectionString = builder["provider connection string"].ToString();
    var newConnectionString = internalConnectionString.Replace("oldDBName", "newDBName");
    builder["provider connection string"] = newConnectionString;
    return builder.ConnectionString;
  }
}
于 2012-07-30T07:35:14.210 回答