How to deal with queries that do not return full entities in Domain Driven Design

domain-driven-design

In my application, I have a listing of information that is deducted from a query that combines information from several entities. In itself, a very common situation.

Now, the corresponding repository method should return a list that contains items of an appropriate type. Clearly, choosing an entity is not appropriate because the information we're dealing with spans across multiple entities. I guess the same applies when querying partial entities. Creating a new entity doesn't make sense either because it would only muddle the model.

I was thinking in the direction of something like creating a DTO in the application layer because the particular query really is there to satisfy an application requirement and not a business requirement.

This essentially leads to introducing the notion of application specific repositories and a dependency on the application layer from those specific repositories.

Somehow this doesn't feel right. Is there a more appropriate approach/pattern I could use here?

Best Answer

IS this a read-only situation? Because that's what it sounds like.

If you're doing DDD, then whenever you need to update/create something in your app you're going to go through the domain model because that is going to contain all of your business logic and validation.

However, there are times in your application when you just want to aggregate together a bunch of data to display to a user in a read-only fashion. In this case, exposing that data through a DTO via a service layer seems perfectly acceptible to me.

I wouldn't do it in the application layer though. I'd expose it as a service facade around my repositories. Let the facade deal with calling the respositories, aggregating the data and generating the DTO. From the application's point of view, it's just getting data with a call to a service. Nothing fancy.

Related Topic