在MVC中更改web.config处的连接字符串

时间:2018-03-05 10:58:45

标签: asp.net-mvc web-config connection-string ef-database-first

我首先使用MVC数据库设置MySQL连接字符串,如下所示:

<add name="wf_workflowEntities" connectionString="metadata=res://*/Models.MySql.Model1.csdl|res://*/Models.MySql.Model1.ssdl|res://*/Models.MySql.Model1.msl;provider=MySql.Data.MySqlClient;provider connection string=&quot;server=192.168.1.8;user id=test;password=abc.1234;CHARSET=utf8;database=wf_workflow&quot;" providerName="System.Data.EntityClient" /> 

如果需要,我想替换连接字符串的一些参数。例如,对于切换服务器,必须再次设置服务器的IP(等用户名,密码)。

我使用此模型发送自定义参数:

public partial class BPMEngine
{
    public string DBServer { get; set; }//ip server
    public string DBName { get; set; }//database name
    public string DBUserName { get; set; }//username
    public string DBPass { get; set; }//password
}

这是观点:

@Html.TextBoxFor(model => model.DBServer, new { @class = "form-control1", placeholder = "ip server" })
@Html.TextBoxFor(model => model.DBName, new { @class = "form-control1", placeholder = "database name" })
@Html.TextBoxFor(model => model.DBUserName, new { @class = "form-control1", placeholder = "username" })
@Html.TextBoxFor(model => model.DBPass, new { @class = "form-control1", placeholder = "password" })
<button type="submit" class="btn btn-block btn-success"  id="transfer">save</button>

但我不知道如何通过控制器(或操作结果)在web.config上更改连接字符串的参数。

事实上,我不知道,我应该在控制器中为这个问题做些什么?

1 个答案:

答案 0 :(得分:1)

您可以使用supplied here方法在运行时更改连接。

// assumes a connectionString name in .config of MyDbEntities
var selectedDb = new MyDbEntities();
// so only reference the changed properties
// using the object parameters by name
selectedDb.ChangeDatabase
(
    initialCatalog: "name-of-another-initialcatalog",
    userId: "jackthelady",
    password: "nomoresecrets",
    dataSource: @".\sqlexpress" // could be ip address 120.273.435.167 etc
);

我认为这是做你需要的更好的方法,处理程序化的web.config修改可能很麻烦,但是,如果你更喜欢使用web.config修改路由,你可以使用this another one

var configuration = WebConfigurationManager.OpenWebConfiguration("~");
var section = 
  (ConnectionStringsSection)configuration.GetSection("connectionStrings");
  section.ConnectionStrings["MyConnectionString"].ConnectionString = "Data Source=...";
configuration.Save();