Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best practices of making a repository class with EF4 code first?

There seem to be many ways to apply the repository patterns that is why i need your opinion and a good clear answer on what seem the best way of applying the repository pattern. It is the generic repository ? But there is a problem where some domain object dont have the same behaviour as others. It is specify repository ? What about code repeatition between repositories? it is both combinaison ? how about using a di container for both kind of implementation ?

Thanks

Edit: the orm i am using is entity framework 4. Would be nice to have an example with EF4.

like image 505
Rushino Avatar asked Oct 13 '22 17:10

Rushino


2 Answers

The Repository pattern itself is pretty explicit in those areas that require specification. The rest is left out on purpose, because it depends on my outside factors, such as your programming language, project scope and your personal programming style.

In other words: You seem to be asking for a pattern on how to apply the pattern, but in the end you will have to take your own decisions when programming.

I will try to reply to your more specific questions though:

  • Yes, using Generics is a good idea for a repository. Another approach would be to have a common interface for all objects that should be stored. You might also go with both, depending on your requirements.
  • Try to deal with differences in object behaviour by calling polymorphic methods on the objects to be stored.
  • There should be no code repetition if you do it right (by using generics and / or interfaces).
like image 171
Adrian Grigore Avatar answered Nov 15 '22 09:11

Adrian Grigore


This post by Gabriel Schenker is a good explanation of the repository pattern. He implements it with NHibernate (you don't say which ORM you are using) and provides a generic base repository. For me the repository pattern is very connected to testing and being able to fake it or mock it and this blog post also shows how to make your own fake.

In my experience most repositories share some common functionality e.g. GetById, Add, Remove. So it is useful to have a base class that can be inherited. Where it can get a little trickier is when you start thinking about dynamic Linq queries and how those can be tested.

Examples of repository patterns with Linq can be found here and here but I would start simple as these could be overkill for some projects.

like image 45
Daniel Lee Avatar answered Nov 15 '22 08:11

Daniel Lee