如何在Entity Framework中手动为不同的数据库连接创建DbContext?
答案 0 :(得分:1)
首先,您可以在App.Config
文件中拥有多个命名连接字符串,如下所示:
<connectionStrings>
<add name="ToDoConnectionString" connectionString="data source=myLocalBox;initial catalog=ToDoDbCodeFirst2;integrated security=True;MultipleActiveResultSets=True;" providerName="System.Data.SqlClient" />
<add name="StackOverflowEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=StackOverflow;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
现在您可以定义从DbContext
类继承的两个不同的自定义类,如下所示:
using System.Data.Entity;
namespace EfDevelopment
{
public class ToDoCodeFirstDbContext : DbContext
{
public ToDoCodeFirstDbContext()
: base("name=ToDoConnectionString")//connection string for 1st DB
{
}
public DbSet<ToDo> ToDos { get; set; }
}
public class ToDoCodeSecondDbContext : DbContext
{
public ToDoCodeSecondDbContext()
: base("name=StackOverflowEntities")//connection string for 2nd DB
{
}
public DbSet<ToDo> ToDos { get; set; }
}
}
现在在你的主程序中(我已经使用了控制台应用程序)根据你需要将它们连接到适当的数据库来实例化相应的实体框架(EF)上下文类,如下所示:
class Program
{
static void Main(string[] args)
{
using (var db = new ToDoCodeFirstDbContext())
{
//write your code here for first DB connection
}
using (var db = new ToDoCodeSecondDbContext())
{
//write your code here for second DB connection
}
}
}