doublnt
doublnt

Reputation: 571

Should I returning IQueryable<T> from a repository in DDD

Recently, I am refactoring my DDD project. When I look at my Repository Layer. I found it return IQueryable< T> in my repository. I am puzzled and should I return IQueryable< T> from a repository in my DDD project in Repository Layer? I usually return IQueryable type in my Repository design. But today I found a opposite idea from this article I can't figure it out!

Upvotes: 4

Views: 1425

Answers (2)

plalx
plalx

Reputation: 43718

You probably shouldn't do that.

The repository's job is not only to abstract away persistence details, but also to provide an explicit query contract defining those that are needed to process commands1 in your domain.

If you feel the need to further filter/transform what's returned from your repository then you most likely failed to capture an explicit query that should be part of the repository's contract.

Having such contract lets the querying clients express their intent and allows for easier optimizations.

1. Nowadays, it's quite common to apply some CQRS principles and by-bass the domain model entirely for queries. Given this scenario, the only queries that would go through the repository are the ones needed to process commands. You are however not forced in any way to use this approach so your repository could fulfill reporting queries as well if you wish.

Upvotes: 1

Constantin Galbenu
Constantin Galbenu

Reputation: 17683

If you return IQueryable you permit domain knowledge leaking from Domain layer to the consumer layers. It increases the risk that your Domain objects will become anemic and all behavior will move to other layers.

Although it seams very handy to return a IQueryable and you think that your code becomes simpler, that is just an illusion; when the project will grow that IQueryable will transform your code into a big ball of mud, with domain code scattered every where. You won't be able to optimize your repository or to change one persistence with another (i.e. from sql to nosql).

Upvotes: 6

Related Questions