A repository, according to the Repository pattern, should provide queries or actual entities?
I am currently refactoring my code for a web application developed using ASP.NET MVC3 with C# and Razor. One of the pattern I am using in order to better structure my application is the Repository pattern, which, besides being a really useful pattern, is also a frequent matter of discussion within the developers' community.
In this context I found an article by Fredrik Normen which states that, according to the definition of Repository,a repository class must provide actual entities (for instance List in .NET) and not queriable objects (I开发者_如何学GoQueriable in .NET). Instead in the NerdDinner tutorial from ASP.NET MVC official website they use IQueriable when the Repository has to provide multiple instances of the same object and the actual entity when the repository has to provide a single instance of the object.
What is the most correct approach to use when modeling a repository class/interface according to the Repository pattern?
Thanks
Francesco
In my opinion this sort of thing is detrimental to the use of your time. ;-)
In theory, your repository should return objects or traditional collections of them, yes. However, even the definition of the repository pattern you link to uses the term "collection-like interface". Certainly, an IQueryable<Entity>
is a 'collection-like' interface, yes?
In practice, I almost never think about the distinction... but I always try to put all of the querying code in the repository. I'd say 90% of my collection-based repository methods return traditional collections, while the other 10% return something based on IQueryable<>
. The exceptions usually have to do with paging; so I can get the totals from the query down the line if needed, and not have to get that info early if I don't need it. It's a little lazy, but it works for me.
But I do think it's a good idea to always try to return traditional collections, because that will mean you are encapsulating all of your querying in the repository, which is where it should be. I would recommend just not to get too caught up in the extreme levels of adhering to someone's idea of what the requirement is for pattern-X
Opinions will differ on that, as you've already found. For small scale applications it's probably OK to let your repositories expose IQueryable.
One thing that you certainly should not do is pass IQueryable to your views. Make sure your views receive only materialized objects and collections (like List or arrays). This way if an error exists in a query somewhere, it will occur in the controller (or repository) and not in your view. This enables you to test the queries and handle errors gracefully.
精彩评论