我首先使用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="server=192.168.1.8;user id=test;password=abc.1234;CHARSET=utf8;database=wf_workflow"" 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 上更改连接字符串的参数。
其实我不知道,这个问题在控制器中我应该怎么做?
您可以使用此处提供的方法在运行时更改连接。
// 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 修改路线,您可以使用另一个。
var configuration = WebConfigurationManager.OpenWebConfiguration("~");
var section =
(ConnectionStringsSection)configuration.GetSection("connectionStrings");
section.ConnectionStrings["MyConnectionString"].ConnectionString = "Data Source=...";
configuration.Save();