IQueryable & Repositories - take 2?

2019-01-07 22:03发布

I have to admit I have been carrying the "Repository should not return IQueryable" banner because it is harder to test. I have been influenced by the answers to other questions like this and this.

This morning I've been reading ScuttGu's blog about ASP.NET vNext where he details Model Binding using a SelectMethod that seems to rely on IQueryable for paging and sorting.

Do you think this will force us to reconsider the role IQueryable plays in repositories?

1条回答
三岁会撩人
2楼-- · 2019-01-07 22:40

DDD Repository should encapsulate data access technicalities:

Definition: A Repository is a mechanism for encapsulating storage, retrieval, and search behavior which emulates a collection of objects.

It is also responsible for handling middle and end of life of domain objects. Repository interface belongs to Domain and should be based on Ubiquitous Language as much as possible. In addition to DDD book, these two articles cover almost everything you need to know when designing repositories:

Exposing IQueryable on the Repository interface is not optimal in my opinion. IQueryable is not part of Ubiquitous Language. It is a technicality, it has no domain meaning. Instead of encapsulating data retrieval Repository would expose bare data access mechanism, which essentially defeats the purpose of having Repository in the first place.

Regarding ASP.NET. This is a UI framework. Why would you allow UI framework to affect the design of you domain model? Microsoft examples often times encourage things like UI data grid binded directly to your database tables. Or, most recently, controls binded to what is referred to as Domain Model, while it is in fact Anemic Model, or simply dumb data container with gets/sets. The quote from the article that you mention (I put some emphasis):

Model binding is a code-focused approach to data-binding. It allows you to write CRUD helper methods within the code-behind file of your page, and then easily wire them up to any server-controls within the page. The server-controls will then take care of calling the methods at the appropriate time in the page-lifecycle and data-bind the data.

My interpretation of this is to ditch the model and objects and just bind your data to UI. This is probably a valid and justified approach in a lot of cases. But since the question was tagged as DDD I would say that in DDD this is called Smart UI Anti-Pattern.

查看更多
登录 后发表回答