King Chan King Chan - 11 months ago 43
C# Question

Why use Repository Pattern or please explain it to me?

I am learning repository pattern and was reading Repository Pattern with Entity Framework 4.1 and Code First
and Generic Repository Pattern - Entity Framework, ASP.NET MVC and Unit Testing Triangle
about how they implement the repository pattern with Entity Framework.


•Hide EF from upper layer

•Make code better testable

Make code better testable I do understand, but why hide EF from upper layer?

Looking at their implementation, it seems just wrap the entity framework with a generic method for query the entity framework. Actually what's the reason for doing this?

I am assuming is for

  1. Loose coupling (that's why hide EF from upper layer?)

  2. Avoid repeat writting same LINQ statement for same query

Am I understand this correctly?

If I write a DataAccessLayer which is a class have methods

QueryFooObject(int id)
..//query foo from entity framework

AddFooObject(Foo obj)
.. //add foo to entity framework
QueryBarObject(int id)

AddBarObject(Bar obj)

Is that also a Repository Pattern?

Explaination for dummy will be great :)

Answer Source

One thing is to increase testability and have a loose coupling to underlying persistance technology. But you will also have one repository per aggregate root object (eg. an order can be an aggregate root, which also have order lines (which are not aggregate root), to make domain object persistance more generic.

It's also makes it much easier to manage objects, because when you save an order, it will also save your child items (which can be order lines).