Is There a Real Advantage to Generic Repository?

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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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();
</code>
<code>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(); </code>
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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
</code>
<code>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 </code>
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

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

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

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.

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.

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

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) :

  • Generic Entity Base Class
  • A Truly Generic Repository, Part 1
  • A Truly Generic Repository, Part 2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật