如何在实体框架中为不同的数据库连接手动创建DbContext?
首先,您可以在 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
}
}
}