DbContext - 存储库和工作单元模式的组合?
问题描述:
想知道我是否可以在这里得到一些指导。在DbContext的MSDN页面(http://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext%28v=vs.103%29.aspx)中,它指出:“表示工作单元和存储库模式的组合,并允许您查询数据库并将所做的更改分组在一起,然后将其作为一个单元写回商店。”DbContext - 存储库和工作单元模式的组合?
我的仓库模式的理解是它在你的数据持久层提供了一个抽象。如何将与EF耦合的东西的具体实现视为抽象?
而且,我会如何利用它作为工作模式的单位?目前,我的工作单位有一个ObjectContext的财产,我的每个回购的一个特性:
public class UnitOfWork : IUnitOfWork
{
private TPSEntities _context = new TPSEntities();
private ICustomerRepository _customerRepository;
private IUsersRepository _UsersRepository;
public ICustomerRepository CustomerRepository
{
get
{
if (_customerRepository == null)
{
_customerRepository = new CustomerRepository(_context);
}
return _customerRepository;
}
}
public IUsersRepository UsersRepository
{
get
{
if (_UsersRepository == null)
{
_UsersRepository = new UsersRepository(_context);
}
return _UsersRepository;
}
}
public void Save()
{
_context.SaveChanges();
}
public void Save(string storedProcedure)
{
_context.SaveChanges();
//_context.ExecuteStoreCommand
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
_context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
然后我注入我的工作对象的单位为通过DI我的控制器,并远离我去。
有没有更好的办法用的DbContext做到这一点?
感谢,
克里斯
答
其实,DbContext
是对数据库的抽象 - 有来自微软的SQL引擎的几个口味,所有工作外的开箱即用的EF,如果你在你的代码中使用EF,那么你必须在引擎之间切换的唯一方法就是连接字符串。
这就是说,它是不寻常的希望又抽象,这次在ORM工具 - EF,你的情况。大多数指南,博客文章等我发现,演示存储库模式,也通过抽象ORM工具来做到这一点。那么,你在你提供的代码中。
我猜它归结为你的“数据库层”和“仓库”的定义 - 尽管我敢肯定有文献严格的定义,这些定义都没有在互联网上是一致的。 (惊讶?:P)
ObjectContext或DbContext不会产生任何逻辑差异。 – 2013-04-04 12:51:11