Repository pattern: Limitation, purpose , and benefits

不羁岁月 提交于 2019-12-10 10:51:28

问题


I am new to repository pattern, and I come up the following questions:

  1. What is/are the purpose of repository pattern?
  2. What is/are the limitation of repository pattern?
  3. What is/are the benefits of repository pattern?
  4. Do the methods below should be exposed in the repository pattern?

public IQueryable<T> GetQuery(){
    return _objectSet;
}

public IEnumerable<T> GetAll(){
    return GetQuery().AsEnumerable();
}

public IEnumerable<T> Find(Expression<Func<T, bool>> predicate){
    return _objectSet.Where(predicate);
}

public T Single(Expression<Func<T, bool>> predicate){
    return _objectSet.Single(predicate); 
}

public T First(Expression<Func<T, bool>> predicate){
    return _objectSet.First(predicate);
}

Any help please?


回答1:


1.What is/are the purpose of repository pattern?

To abstract away the data source to reduce complexity. By doing so the caller do not have to have any knowledge about the data source or it's quirks. They just know that they can invoke the repository and get information from an arbitary data source.

2.What is/are the limitation of repository pattern?

It's only used to abstract away the data source.

A soft limit is that people find it hard to understand how to design the repository classes. It's common that people make the repositories to generic which in turn leaks DB implementation to the invoker, thus forcing the caller to have DB specific knowlegde (or OR/M knowledge). Those implementations are seriously flawed and provide no benefit over using OR/Ms directly.

3.What is/are the benefits of repository pattern?

Less complex code. The caller get's less complex since they only have to invoke a method in the repository to fetch and store information in the data source. And the Data Access Layer get's less complex sinvce the repositories only focuses on retreiving and storing information.

4.Do the methods below should be exposed in the repository pattern?

No. IQueryable<T> leaks DB specific information. You need for instance to know how the OR/M handles translates LINQ to IN SQL clauses and how the OR/M is configured for lazy/eager loading.

To reduce complexity the repository should communicate what kind of queries it support. Using Expression<Func<T, bool>> predicate is like saying throw anything at me and I'll try to handle it. Won't work very well. Again. Take the IN clause as an example. The LINQ statement for it varies between different OR/Ms.

Using expressions also move the responsibility of constructing correct queries to the caller. That means that the unit tests for the caller also have to include tests for validating that the caller makes correct queries. i.e. more complex tests.



来源:https://stackoverflow.com/questions/9900485/repository-pattern-limitation-purpose-and-benefits

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!