31

Was reading through some articles on the advantages of creating Generic Repositories for a new app (example). The idea seems nice because it lets me use the same repository to do several things for several different entity types at once:

IRepository repo = new EfRepository(); // Would normally pass through IOC into constructor 
var c1 = new Country() { Name = "United States", CountryCode = "US" };
var c2 = new Country() { Name = "Canada", CountryCode = "CA" };
var c3 = new Country() { Name = "Mexico", CountryCode = "MX" };
var p1 = new Province() { Country = c1, Name = "Alabama", Abbreviation = "AL" };
var p2 = new Province() { Country = c1, Name = "Alaska", Abbreviation = "AK" };
var p3 = new Province() { Country = c2, Name = "Alberta", Abbreviation = "AB" };
repo.Add<Country>(c1);
repo.Add<Country>(c2);
repo.Add<Country>(c3);
repo.Add<Province>(p1);
repo.Add<Province>(p2);
repo.Add<Province>(p3);
repo.Save();

However, the rest of the implementation of the Repository has a heavy reliance on Linq:

IQueryable<T> Query();
IList<T> Find(Expression<Func<T,bool>> predicate);
T Get(Expression<Func<T,bool>> predicate);
T First(Expression<Func<T,bool>> predicate);
//... and so on

This repository pattern worked fantastic for Entity Framework, and pretty much offered a 1 to 1 mapping of the methods available on DbContext/DbSet. But given the slow uptake of Linq on other data access technologies outside of Entity Framework, what advantage does this provide over working directly with the DbContext?

I attempted to write a PetaPoco version of the Repository, but PetaPoco doesn't support Linq Expressions, which makes creating a generic IRepository interface pretty much useless unless you only use it for the basic GetAll, GetById, Add, Update, Delete, and Save methods and utilize it as a base class. Then you have to create specific repositories with specialized methods to handle all the "where" clauses that I could previously pass in as a predicate.

Is the Generic Repository pattern useful for anything outside of Entity Framework? If not, why would someone use it at all instead of working directly with Entity Framework?


Original link doesn't reflect the pattern I was using in my sample code. Here is an (updated link).

3
  • 3
    something of interest ayende.com/blog/3955/repository-is-the-new-singleton
    – kenny
    Sep 7, 2012 at 0:40
  • 1
    Is the question really about "advatange of generic repository" or is is more "how to hide complex queries behind a generic repository interface"? Is it possible to be generic if its interface and usage depends on linq? Our Repositoryapi has a QueryByExample method that is completely independant of the search technique and would allow to shift implementation.
    – k3b
    Sep 7, 2012 at 4:55
  • "It lets me use the same repository to do several things for several different entity types" => Is it me or you just misunderstood what a generic repository is (including with regard to the mentioned article) ? To me, generic repository has always meant templating all repos with a single class or interface, not having a single repository instance managing the persistence of all entities whatever their type... Sep 7, 2012 at 11:52

6 Answers 6

39

Generic repository is even useless (and IMHO also bad) for Entity Framework. It doesn't bring any additional value to what is already provided by IDbSet<T> (which is btw. generic repository).

As you have already found the argument that generic repository can be replaced by implementation for other data access technology is pretty weak because it can demand writing your own Linq provider.

The second common argument about simplified unit testing is also wrong because mocking repository / set with in-memory data storage replaces Linq provider with another one which has different capabilities. Linq-to-entities provider supports only subset of Linq features - it even doesn't support all methods available on IQueryable<T> interface. Sharing expression trees between data access layer and business logic layers prevents any faking of data access layer - query logic must be separated.

If you want to have strong "generic" abstraction you must involve other patterns as well. In this case you need to use abstract query language which can be translated by repository to specific query language supported by used data access layer. This is handled by Specification pattern. Linq on IQueryable is specification (but the translation requires provider - or some custom visitor translating expression tree into query) but you can define your own simplified version and use it. For example NHibernate uses Criteria API. Still the simplest way is using specific repository with specific methods. This way is the simplest to implement, simplest to test and simplest to fake in unit tests because the query logic is completely hidden and separated behind the abstraction.

8
  • Just a quick question, NHibernate has the ISession which is easily mockable for general unit testing purposes, and I'd gladly drop the 'repository' when working with EF too - but is there any easier, straightforward way to recreate that? Something akin to ISession and the ISessionFactory, 'cause there's no IDbContext as far as I can tell... Sep 8, 2012 at 15:04
  • No there is no IDbContext - if you want IDbContext you can simply create one and implement it on your derived context. Sep 8, 2012 at 15:14
  • So you're saying that for everyday MVC apps, IDbSet<T> should provide a good enough generic repository to forget about the repository pattern completely. Except for special situations e.g where you aren't allowed any DAL references in your MVC project.
    – ProfK
    Mar 10, 2013 at 10:45
  • 1
    Good answer. Some developers creates just another layer of abstractions without any reason. IMO, EF do not need generic repository nor a unit of work (they are build-in)
    – ashraf
    Mar 11, 2013 at 23:30
  • 1
    IDbSet<T> is a generic repository with a dependency on the Entity Framework which kind of defeats the purpose of using a generic repository to abstract away the dependency on the Entity Framework. Oct 8, 2013 at 22:33
7

The issue isn't the repository pattern. Having an abstraction between getting data and how you're getting it is a good thing.

The issue here is the implementation. Assuming that an arbitrary expression will work for filtering is dicey at best.

Making a repository work for all of your objects directly kinda misses the point. Data objects will rarely if ever map directly to business objects. Passing in T to filter makes a lot less sense in these situations. And providing that much functionality pretty much guarantees that you can't support all of it once a different provider comes along.

5
  • So it makes more sense to have a Repository per data object, or group of tightly related objects, with specific methods like GetById(int id), SortedList(), etc? Am I returning lists of data objects from a repository, or transforming them to business objects with the necessary fields as well? Kinda thought that was what happened in the Service/Business layer.
    – Sam
    Sep 7, 2012 at 2:16
  • 1
    @sam - I tend to favor more specific repositories, yes. If they're doing translation or not depends on where things are likely to change. If your domain is well defined, I'd return things in the shape of the domain. If the data is well defined, I'd return things in the shape of the data structures. If neither are, I'd have an entity that serves as the well defined basis to build off of and then adapt to/from that.
    – Telastyn
    Sep 7, 2012 at 2:23
  • 1
    There's no reason you can't have specific repositories that delegate the common stuff to a generic repository, but also have additional repository-specific methods for more complex calls. I've seen it done that way several times.
    – Eric King
    Sep 7, 2012 at 17:06
  • @EricKing I have too, and it was good there, but it tends to leak some abstraction since the common stuff tends to only exist due to commonality of how the data is stored (GetByID for example requires tables with IDs).
    – Telastyn
    Sep 7, 2012 at 17:31
  • @Telastyn Yes, I would agree with that, but it happens with specific repositories, too. Leaky abstractions are not specific to generic repositories. (Wow, could I have phrased that any more clumsily?)
    – Eric King
    Sep 7, 2012 at 17:36
2

The value of a generic data layer (a repository is a particular type of data layer) is allowing the code to change the underlying storage mechanism with little or no impact on the calling code.

In theory, this works well. In practice, as you have observed, the abstraction is often leaky. The mechanisms used to access data in one are different to the mechanisms in another. In some cases, you end up writing the code twice: once in the business layer and repeating it in the data layer.

The most effective way of creating a generic data layer is to know the different types of data sources the application will use beforehand. As you have seen, assuming LINQ or SQL is universal can be a problem. Trying to retrofit new data stores will likely result in a rewrite.

[Edit: Added the following.]

It also depends on what the application needs from the data layer. If the application is just loading or storing objects, the data layer can be very simple. As the need to search, sort and filter increases, the complexity of the data layer increases and abstractions start to become leaky (such as exposing LINQ queries in the question). Once users can supply their own queries, however, the cost/benefit of the data layer needs to be carefully weighed.

1

Having a code layer above the database is worthwhile in almost all cases. I would generally prefer a "GetByXXXXX" pattern in said code -- it lets you optimize queries behind it as needed while keeping the UI free of data interface clutter.

Taking advantage of generics is definitely fair game -- having a Load<T>(int id) method makes tons of sense. But building repositories around LINQ is the 2010s equivalent of dropping sql queries everywhere with a little added type safety.

0

Well, with the link provided I can see that it may be a handy wrapper for a DataServiceContext, but does not reduce code manipulations nor improves readability. Besides, access to DataServiceQuery<T> is obstructed, limiting flexibility to .Where() and .Single(). Nor are AddRange() or alternatives provided. Nor is Delete(Predicate) provided which could be useful ( repo.Delete<Person>( p => p.Name=="Joe" ); to delete Joe-s). Etc.

Conclusion: such an API obstructs the native API and limits it to a few simple operations.

2
  • You are correct. That wasnt the article using the pattern I have in my sample code. Will try to find the link when I get home.
    – Sam
    Sep 7, 2012 at 1:27
  • Updated link added to bottom of question.
    – Sam
    Sep 7, 2012 at 1:54
-1

I would say "Yes". Depending on your data model, a well-developed Generic Repository can make the data access tier leaner, neater, and much more robust.

Read this series of articles (by @chris-pratt) :

Not the answer you're looking for? Browse other questions tagged or ask your own question.