Using extension methods to filter IQueryable data collections

As I talked about in my post Do we need the repository pattern? I’ve been thinking about how we can make a testable data access layer with Entity Framework without using a repository pattern. I showed how you could do that in my post Mocking your Entity Framework data context and testing it in .NET MVC. However losing the repository also loses a nice centralised place to keep your query logic. In this post I’ll show you a nice simple way to use extension methods to do this.

Suppose you’re using Entity Framework to store a collection of foos and there are several places in your app that you want to show a list of foos that are special in some way. You want to keep the logic for foo specialness in a central place as you don’t want to repeat it. An extension method gives us a really nice way of doing this.

Here is how our extension method would be used:

var specialFoos = _data.Foos.WhereSpecial();

And here is the implementation:

public static class ModelFilters
{
  public static IQueryable<Foo> WhereSpecial(this IQueryable<Foo> foos)
  {
    return foos.Where(f => f.IsSpecial && HowSpecial(f) > 10);
  }
}

Now all your query logic is in one place and you can test it because the extension method is on the IQueryable interface rather than a concrete collection class.