我计划使用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)
}
}
如果我从控制器中调用IRepository和IUnitOfWork,如何知道匹配的上下文?这个问题的最佳实践是什么?
IRepository repositoryStudent = new Repository<StudentViewModel>()
等等。 - derodevilBaseController
不是初始化UoW的正确位置。相反,它应该在业务流程级别上根据需求基于DbContext创建特定的UoW,然后获取特定的repositories。 - ramiramilu