Setup Entity Framework For Dynamic Connection String

前端 未结 3 2004
一生所求
一生所求 2020-11-30 05:14

I am working on an app that will use the same database schema across multiple databases. For this reason, I\'ve created a database called MyTemplate. When a new

3条回答
  •  伪装坚强ぢ
    2020-11-30 05:19

    Nicholas Butler's answer is quite correct. In addition to what he said, I was faced with the problem of taking an existing connection string for entity framework and just pointing it at a different database that had the same structure. I used the following code to change only the data source of the existing string:

    var originalConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["CSName"].ConnectionString;
    var ecsBuilder = new EntityConnectionStringBuilder(originalConnectionString);
    var sqlCsBuilder = new SqlConnectionStringBuilder(ecsBuilder.ProviderConnectionString)
    {
        DataSource = "newDBHost"
    };
    var providerConnectionString = sqlCsBuilder.ToString();
    ecsBuilder.ProviderConnectionString = providerConnectionString;
    
    string contextConnectionString = ecsBuilder.ToString();
    using (var db = new SMSContext(contextConnectionString))
    {
        ...
    }
    

提交回复
热议问题