在运行时切换EF连接字符串

时间:2014-04-11 14:08:26

标签: c# asp.net-mvc entity-framework

我知道这个问题已经被问过并已经回答了几次,但我遇到的每一个答案都是不完整的,过于模糊的或者假设比我更多的必备知识。我正在寻找逐步说明,用相当简单的英语,在我的默认连接字符串中换出数据库,以获取将在表中查找的数据库名称。我一直在看这段代码......

    public DFDBEntities(string connectionString)

        : base(connectionString)
    {

    }

......但没有人真正解释如何以及在何处实施它。假设我有一个名为" db"代表我的DataModel.EDMX模型...

    private DataModel db = new DataModel();

...如何将与该类关联的连接字符串更改为指向不同的物理数据库(具有相同的数据结构)?

3 个答案:

答案 0 :(得分:1)

通过使用默认构造函数,您基本上是说“我想使用web.config中指定的默认连接字符串”

DbContextconstructor overload,允许您覆盖默认连接字符串,您只需将其传递给

db = new DataModel("MyConnectionStr");

答案 1 :(得分:1)

尝试:

 private DataModel db = new DataModel(yourconnectionString);

答案 2 :(得分:0)

您可以使用辅助类来进行连接设置,例如

public class EntityConnectionStringHelper
    {
        public static string Build()
        {
            string serverName = "******";
            string databaseName = "****";
            string password = "****";
            string userid = "*****";
            string meta = "********";
            return EntityConnectionStringHelper.Build(serverName, databaseName, userid, password, meta);
        }
        public static string Build(string serverName, string databaseName, string userName, string password, string metaData)
        {
            // Specify the provider name, server and database.
            string providerName = "System.Data.SqlClient";
            return EntityConnectionStringHelper.Build(providerName, serverName, databaseName, userName, password, metaData);
        }
        public static string Build(string providerName, string serverName, string databaseName, string userName, string password, string metaData)
        {
            // Initialize the connection string builder for the
            // underlying provider.
            SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();

            // Set the properties for the data source.
            sqlBuilder.DataSource = serverName;
            sqlBuilder.InitialCatalog = databaseName;
            sqlBuilder.IntegratedSecurity = false;
            sqlBuilder.UserID = userName;
            sqlBuilder.Password = password;

            // Build the SqlConnection connection string.
            string providerString = sqlBuilder.ToString();

            // Initialize the EntityConnectionStringBuilder.
            EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();

            //Set the provider name.
            entityBuilder.Provider = providerName;

            // Set the provider-specific connection string.
            entityBuilder.ProviderConnectionString = providerString;

            // Set the Metadata location.
            entityBuilder.Metadata = string.Format(@"res://*/{0}.csdl|res://*/{0}.ssdl|res://*/{0}.msl", metaData);

            return entityBuilder.ToString();
        }
    }

对于您的实体,您可以使用

获取实例
DFDBEntities context = new DFDBEntities (EntityConnectionStringHelper.Build());