我正在爲我的應用程序開發通用存儲庫,我在這裏有一些疑問。通用存儲庫問題
這是一些我對通用的存儲庫中的代碼:
public interface IEntityRepository<T> where T : class
{
void Add(T entity);
T GetById(int id);
IEnumerable<T> Get(Expression<Func<T, bool>> predicate);
IEnumerable<T> GetAll();
}
public class EntityRepository<T> : IDisposable, IEntityRepository<T> where T : class
{
protected DbSet<T> DbSet;
protected DbContext Context;
public EntityRepository(DbContext dataContext)
{
DbSet = dataContext.Set<T>();
Context = dataContext;
}
public void Add(T entity)
{
DbSet.Add(entity);
}
public IEnumerable<T> Get(Expression<Func<T, bool>> predicate)
{
return DbSet.Where(predicate);
}
public IEnumerable<T> GetAll()
{
return DbSet;
}
public T GetById(int id)
{
return DbSet.Find(id);
}
// IDisposable
public void Dispose()
{
if (Context != null)
{
Context.Dispose();
}
GC.SuppressFinalize(this);
}
}
什麼我遇到困難是這樣的:
1 - 我應該返回的IEnumerable從倉庫層服務層而不是IQueryable?我已經閱讀了關於這個主題的一些關於網絡的文章,但是找不到這個問題的一個明確的或合理的明確的答案。通過返回IEnumerable,所有後續查詢將在本地完成?
2 - 顯然需要的一件事是能夠檢索分頁數據。我不想獲得10萬條記錄只是爲了顯示50.我的問題是,如果這個「邏輯」應該在存儲庫或服務,即服務獲取所有數據,然後跳過/需要但它需要或存儲庫已經只返回服務需要的數據?還是應該將這些類型的方法放在繼承通用類的特定存儲庫中?
在此先感謝
我認爲回購應該儘可能愚蠢,只是一個DbSet的包裝。也許這麼愚蠢,你開始問自己,爲什麼我首先需要他們?這確實是[正在進行的辯論](http://stackoverflow.com/a/5626884/861716)。順便說一下,在回購之外擁有DbContext是一個不錯的選擇。 –