我已经为一些简单的数据检索创建了一个非常简单的存储库,并且想知道我是否在朝着正确的方向前进。有人对此有什么想法吗?
interfacepublic interface IRepository<T> where T : class {
IEnumerable<T> GetAll();
T GetById(int id);
IEnumerable<T> Filter(Expression<Func<T, bool>> filter);
void Dispose();
} classpublic class JobRepository : IRepository<Job>, IDisposable{
/// <summary>
/// handles all job data retrieval
/// crude but will suffice for now
/// </summary>
CentralRepositoryContainer _context = null;
public JobRepository() {
CentralRepositoryContainer context =
HttpContext.Current.GetCentralRepositoryContext();
}
/// <summary>
/// returns all jobs
/// </summary>
/// <returns>IEnumerable<Job></returns>
public IEnumerable<Job> GetAll() {
try {
return this._context.Jobs;
} catch (SqlException ex) {
//error so dispose of context
this.Dispose();
//wrap and rethrow back to caller
throw new CentralRepositoryException("Error getting all jobs", ex);
}
}
/// <summary>
/// return job
/// </summary>
/// <param name="id">integer to search on</param>
/// <returns>job</returns>
public Job GetById(int id) {
try {
return this._context.Jobs.SingleOrDefault(j => j.JobId == id);
} catch (SqlException ex) {
//error so dispose of context
this.Dispose();
//wrap and rethrow back to caller
throw new CentralRepositoryException("Error getting all job by id", ex);
}
}
/// <summary>
/// filters based on parsed filter expression
/// </summary>
/// <param name="filter">filter to search on</param>
/// <returns>IQueryable<Job></returns>
public IEnumerable<Job> Filter(System.Linq.Expressions.Expression<Func<Job, bool>> filter) {
try {
return this._context.Jobs.Where(filter);
} catch (SqlException ex) {
//error so dispose of context
this.Dispose();
//wrap and rethrow back to caller
throw new CentralRepositoryException("Error getting all job by filter", ex);
}
}
public void Dispose() {
if (this._context != null) {
this._context.Dispose();
}
}
}发布于 2011-10-11 13:32:44
特别是在这样简单的情况下,您不希望在EF上创建存储库(我假设它是EF --但对于Linq2SQL也是如此)。
DbContext基本上是存储库模式的实现。您的存储库在顶部只是创建了另一层复杂性,而实际上并没有提供任何真正的好处。
当然,在更复杂的情况下,用特定的接口包装DbContext可能是有意义的。
发布于 2011-10-26 14:56:28
我将对存储库进行一些扩展,向接口添加一些操作并实现它们,并使GetAll()和Filter()方法返回IQueryable (因为它们是查询):
public interface IRepository<T> where T : class {
IQueryable<T> GetAll();
T GetById(int id);
T GetOne(Expression<Func<T, bool>> filter);
IQueryable<T> Filter(Expression<Func<T, bool>> filter);
int Add(T instance); // returns a unique integer ID for this entity.
void Update(T instance);
void Delete(T instance);
void DeleteById(int id);
void Dispose();
}您还可能希望收紧存储库中存储的内容,即不要仅仅是'where T: class‘-让类实现一个具有某些固有特性的基类的接口或下降:
public abstract class BaseEntity {
private int id;
public int Id
{
get
{
return this.id;
}
private set
{
this.id = this.SetId(value);
}
}
protected abstract int SetId(int id);
}作为开始。
https://codereview.stackexchange.com/questions/5586
复制相似问题