【发布时间】:2014-09-28 07:03:16
【问题描述】:
我计划使用 ASP.NET MVC 和 Entity Framework 6 (Code First / POCO) 开发一个 Web 应用程序。我还想在我的应用程序中使用通用存储库和工作单元模式。这个应用程序连接到两个以上的数据库,所以我必须在应用程序中使用多个 DbContext。
public class ContextOne : DbContext
{
public DbSet<Model_One1>
public DbSet<Model_One2>
}
public class ContextTwo : DbContext
{
public DbSet<Model_Two1>
public DbSet<Model_Two2>
}
public class ContextThree : DbContext
{
public DbSet<Model_Three1>
public DbSet<Model_Three2>
}
public interface IRepository<T> where T : DbContext
{
void Add<T>(T entity) where T : class;
}
public class Repository<T> where T : DbContext
{
void Add<T>(T entity) where T : class
{
//T is DbContext and Model. So confusing
}
}
public interface IUnitOfWork<IRepository>
{
}
public class UnitOfWork<IRepository>
{
//IRepository contains more than one DbContext how can I initiate them here?
}
//in application should look like this
public class BaseController : Controller
{
protected IRepository repository = new .. //here I have no idea with multiple DbContext
}
public class HomeController : BaseController
{
public ActionResult Add(Model_Two2 model)
{
base.repository.Add<Model_Two2>(model)
}
}
如果我从 Controller 调用 IRepository 和 IUnitOfWork 我如何知道匹配的上下文?这个问题的最佳实践是什么?
【问题讨论】:
标签: c# asp.net-mvc design-patterns