1

I am busy with a new project and am working on my repository layer. This will be my 2nd project using the Repository Pattern. I have been reading Scott Millett's book Professional ASP.NET Design Patterns In referencing the case study in the book, Scott has used the Query Object Pattern in in his repository interfaces. In my previous project I used LINQ for this purpose and it worked well.

My question is as follows: What are the pros and cons of using a Query Object Pattern implementation versus using LINQ in your repository?

Here are 2 scenarios which illustrate the 2 different approaches:

1. Query Object Pattern approach

public interface IReadOnlyRepository<T, TId> where T : IAggregateRoot
{
    T FindBy(TId id);
    IEnumerable<T> FindAll();
    IEnumerable<T> FindBy(Query query);
}

2. LINQ approach

public interface IReadOnlyRepository<T, TId> where T : IAggregateRoot
{
    T FindBy(TId id);
    IQueryable<T> FindAll();
    IQueryable<T> FindBy(Expression<Func<T, bool>> query);
}

Any contributions would be helpful.

Ozzy
  • 964
  • 1
  • 10
  • 21

1 Answers1

1

Although I think the expression trees of LINQ are just a special form of the query object pattern, because of their greater flexibility, they allow you to introduce bugs in your code that only are visible at runtime. I am talking about C# code that gets successfully converted to an expression tree, but is not understood by the provider that is supposed to translate it to SQL.

Example:

var a = new SpecialObject();
yourRepository.FindBy(x => a.IsCorrect(x));

An error like this would be impossible with an ordinary query object.

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
  • So Daniel, to confirm my understanding, am I correct in that are you saying that the flexible nature of LINQ can result in scenarios where code compile, but it is actually not valid? – Ozzy Aug 18 '11 at 09:09
  • Yes, most definitely! See [here](http://stackoverflow.com/questions/1920775/why-would-entity-framework-not-be-able-to-use-tostring-in-a-linq-statement) for one of many examples. – Daniel Hilgarth Aug 18 '11 at 09:38
  • Or just [google](http://www.google.com/search?hl=en&q=%22LINQ+to+Entities+does+not+recognize+the+method+%27%2A%27+method%2C+and+this+method+cannot+be+translated+into+a+store+expression.%22&oq=%22LINQ+to+Entities+does+not+recognize+the+method+%27*%27+method%2C+and+this+method+cannot+be+translated+into+a+store+expression.%22&aq=f&aqi=&aql=&gs_sm=e&gs_upl=3041l3041l0l5273l1l1l0l0l0l0l0l0ll0l0) the exception message that occurs in a case like this. – Daniel Hilgarth Aug 18 '11 at 09:43