近一年后,我开始一个新的mvc项目,这次是版本4.我想知道以下存储库模式的实现是否比优点更多的缺点。存储库模式+工作单元
public interface IRepository<T> where T : class
{
IEnumerable<T> GetAll();
IQueryable<T> Query(Expression<Func<T, bool>> filter);
void Add(T entity);
void Remove(T entity);
}
public interface IUnitOfWork
{
void Commit();
}
public interface IDbContext : IDisposable
{
IDbSet<T> Set<T>() where T : class;
int SaveChanges();
}
public class DbContextAdapter : IDbContext
{
private readonly DbContext _myRealContext;
public DbContextAdapter()
{
this._myRealContext = new EstafaContext();
}
public void Dispose()
{
_myRealContext.Dispose();
}
public IDbSet<T> Set<T>() where T : class
{
return _myRealContext.Set<T>();
}
public int SaveChanges()
{
return _myRealContext.SaveChanges();
}
}
public class SqlRepository<T> : IRepository<T> where T : class
{
private IDbSet<T> _dbSet;
public SqlRepository(IDbContext dbContext)
{
this._dbSet = dbContext.Set<T>();
}
public IEnumerable<T> GetAll()
{
return this._dbSet.ToList();
}
public IQueryable<T> Query(Expression<Func<T, bool>> filter)
{
return this._dbSet.Where(filter);
}
public void Add(T entity)
{
this._dbSet.Add(entity);
}
public void Remove(T entity)
{
this._dbSet.Remove(entity);
}
}
public class SqlUnitOfWork : IDisposable, IUnitOfWork
{
private IDbContext _dbContext;
private SqlRepository<Cliente> _clientes ;
public SqlUnitOfWork()
{
this._dbContext = new DbContextAdapter();
}
public void Dispose()
{
if (this._dbContext != null)
{
this._dbContext.Dispose();
}
GC.SuppressFinalize(this);
}
public IRepository<Cliente> Clientes
{
get { return _clientes ?? (_clientes = new SqlRepository<Cliente>(_dbContext)); }
}
public void Commit()
{
this._dbContext.SaveChanges();
}
}
这样我就可以通过SqlUnitOfWork从单一点管理所有存储库。 我在之前的项目中使用过这种设计,效果很好,但我觉得效率不高,也许是多余的。 值得添加这样一个抽象层吗?
在此先感谢!
[实现存储库,返回从EF实体映射的域模型]的可能副本(http://stackoverflow.com/questions/13387858/implementing-a-repositoryt-that-returns-a-domain-model -def-from-ef-entit) –
jgauffin
你也可以在这里阅读我的答案:http://stackoverflow.com/questions/10190384/repository-pattern-implementation/10190432#10190432 – jgauffin