How can I query cross tables with Repository Pattern?

倖福魔咒の 提交于 2019-12-09 15:52:04

问题


In my asp.net mvc 3 application, I'm using the repository pattern. I have 3 entities, Company, Country, City. Each of them has their own repository. Company entity has FoundedCountry and FoundedCity foreign keys. Now in a view, I want to show the company details. In this view I want to view Company details as well as, FoundedCountry name and FoundedCity name. In my opinion I have to handle this with a kind of JOIN query. But I'm stuck at how to achieve this in repository pattern. How can I handle this JOIN in repository pattern?

Thank you.


回答1:


The repository should have a task-based interface. This means that ORM's, joins etc are inside the repository. The app just sees an interface whtch returns an object that it can use.

This means you don't create a repository around a table (it pretty much defeats the purpose). In your scenario I suggest you have (at least) 2 repositories: one will handle everything related to updating the model and the other will serve only reads (queries).

This means the query repository will return only the data you want (it basically returns view model bits). Of course, the actual tables and joins are an implementation detail of the repository.




回答2:


Don't construct your repository pattern in a way that is preventing joins! This usually means to use the same ORM context (DataContext/ObjectContext) for all instances associated with the current HTTP request.

I consider it to be an anti-pattern to have a generic IRepository because database access is rarely constrained to a single type of entity at the same time.

You could consider the DataContext/ObjectContext to be a repository by itself.

A last advice: If you don't know what a repository abstraction is good for - don't use one.



来源:https://stackoverflow.com/questions/10288695/how-can-i-query-cross-tables-with-repository-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!