关于如何使用泛型类与工作单元模式一起实现存储库模式,有几个很好的博客。实体框架存储库模式为什么不返回Iqueryable?
Implementing a Data Access Layer with Entity Framework 6.1
Implementing the Repository and Unit of Work Patterns
理念是,定义一个通用接口IRepository和类信息库,它隐藏该数据实际上是如何访问。它可以使用实体框架DbContext进行访问,也可以将知识库作为内存集合进行单元测试。
public interface public interface IRepository<T> where T : class
{
T GetById(int Id);
void DeleteById(int Id);
void Add(T entity);
void Update(T entity);
etc.
}
常常我看到添加几个查询功能类似于可查询和/或可枚举函数。
比如在Implementing a data access layer我看到:
/// Returns an IEnumerable based on the query, order clause and the properties included
/// <param name="query">Link query for filtering.</param>
/// <param name="orderBy">Link query for sorting.</param>
/// <param name="includeProperties">Navigation properties seperated by comma for eager loading.</param>
/// <returns>IEnumerable containing the resulting entity set.</returns>
IEnumerable<T> GetByQuery(Expression<Func<T, bool>> query = null, Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null, string includeProperties = "");
/// <summary>
/// Returns the first matching entity based on the query.
/// </summary>
/// <param name="predicate"></param>
/// <returns></returns>
T GetFirst(Expression<Func<T, bool>> predicate);
如果接口有一个功能的IQueryable GetQuery(),那么我就不会做功能,如GetFirst()和GetByQuery()。
问题:为什么不推荐这么做?人们能否以不希望的方式改变数据?
嘿,它是从这个博客的文本复制粘贴:https://programmingwithmosh.com/entity-framework/common-mistakes-with-the-repository-pattern/。 你应该提到这个信息“借” - ))) –