我有一个MVC项目(首先是数据库),其中有一个string.for,应用这个连接,我使用这种方式,它正确地连接:
但是,我的问题是在运行时使用MySQL database.In事实应用另一个连接,我有几个表单需要SQL连接,还有几个表单需要MySQL connection.On,必须在运行时设置MySQL连接。
因此,我有两个重要的问题:
如何在运行时(关联我的模型)设置MySQL连接字符串?
2-如何在运行项目的不同视图中切换两个连接。
要了解更多的解释,您可以看到我创建MySQL连接的模型如下:(这些字段是在视图中设置的,在提交视图连接之后必须连接)
public partial class BPMEngine
{
public int EngID { get; set; }
public string EngName { get; set; }
public string DBServer { get; set; }
public string DBName { get; set; }
public string DBUserName { get; set; }
public string DBPass { get; set; }
public string EngURL { get; set; }
public string AppRootPath { get; set; }
}发布于 2018-01-22 08:50:28
在应用程序设置中,指定连接字符串,在上下文类中传递连接字符串。
我建议您指定2(或根据需要)连接字符串,并使用多个上下文类,每个类用于与其他DB“通信”。
示例:
在App.config中
<connectionStrings>
<add name="conn_str_number_1" .../>
<add name="conn_str_number_2" .../>
</connectionStrings>上下文类:
class MyContext1 : DbContext
{
public MyContext() : base("name=conn_str_number_1")
{
//...
}
//...
}另一个:
class MyContext2 : DbContext
{
public MyContext() : base("name=conn_str_number_2")
{
//...
}
//...
}并且在代码中使用两个上下文类,这样您就可以与两个DB交互。
若要在运行时切换连接字符串,可以使用contextClass.Database.Connection.ConnectionString属性。More info about it here.
在这里,我们还可以看到:DbContext有一个构造函数重载,它接受连接字符串或连接字符串本身的名称。实现您自己的版本并将其传递给基本构造函数:
public class MyDbContext : DbContext
{
public MyDbContext( string nameOrConnectionString )
: base( nameOrConnectionString )
{
}
}但是您必须在运行程序之前指定所有连接字符串:)
https://stackoverflow.com/questions/48377433
复制相似问题