Being fairly new to Asp.Net MVC I am following the SportsStore example from the book Pro ASP.Net MVC 3 Framework.
All is going fine, but now I start to enhance the base example with some extra entities. Which is the better approach: - should each entity have its own repository (which would seem to duplicate code) or - should there be a generic repository for similar entities?
Are there any other projects out there that the same architecture are more complete samples?
It reduces redundancy of code. It force programmer to work using the same pattern. It creates possibility of less error. If you use this pattern then it is easy to maintain the centralized data access logic.
It depends on your logic and how "important" are every entity. For example, if you had the entities User and Address you could have UserRepository and AddressRepository. But only UserService, with methods like addAddress(User user, Address address)... Save this answer.
It is a data access pattern that prompts a more loosely coupled approach to data access. We create a generic repository, which queries the data source for the data, maps the data from the data source to a business entity, and persists changes in the business entity to the data source.
The Repository pattern makes it easier to test your application logic. The Repository pattern allows you to easily test your application with unit tests. Remember that unit tests only test your code, not infrastructure, so the repository abstractions make it easier to achieve that goal.
This is something that is heavily debated on the internet. If you use the search here at SO you can find plenty of threads about it. In the end is just comes down to your personal preference. Try both options and decide which one is best for you.
I started creating separate repositories for every entity, but it felt like loads of unnecessary work (and lots of code duplication), so recently I started using generic repositories, and that's working out perfectly for me.
See this thread for more information: Advantage of creating a generic repository vs. specific repository for each object?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With