mko
mko

Reputation: 7325

Query data across multiple repositories in DDD

I am using multiple aggregate roots inside a DDD bounded context.

For example

public class OrderAggregate
{
    public int ID {get;set;}
    public string Order_Name {get;set;}
    public int Created_By_UserID {get;set;}
}

public class UserAggregate
{
    public int ID {get;set;}
    public string Username {get;set;}
    public string First_Name {get;set;}
    public string Last_Name {get;set;}
}

I am using SQL relational base to persists domain objects. Each aggregate root matches one repository.

In case I would like to find an order that was created by John Doe (seach accross multiple aggregates) what would be a DDD way to go?


public class QueryOrderAggregate
{
    public int ID { get; set; }
    public string Order_Name { get; set; }
    public int Created_By_UserID { get; set; }
    public string First_Name { get; set; }
    public string Last_Name { get; set; }
}

Upvotes: 1

Views: 3112

Answers (1)

VoiceOfUnreason
VoiceOfUnreason

Reputation: 57257

In case I would like to find an order that was created by John Doe (seach accross multiple aggregates) what would be a DDD way to go?

Almost the same way that it goes with accessing an aggregate...

You create a Repository that provides a (whatever the name for this view/report is in your domain). It probably uses the UserId as the key to identify the report. In the implementation of the repository, the implementation can do whatever makes sense -- a SQL join is a reasonable starting point.

The View/Report is basically a value type; it is immutable, and can provide data, but doesn't not have any methods, or any direct access to the aggregate roots. For example, the view might include the OrderId, but to actually get at the order aggregate root you would have to invoke a method on that repository.

A view that spans multiple aggregates is perfectly acceptable, because you can't actually modify anything using the view. Changes to the underlying state still go through the aggregate roots, which provide the consistency guarantees.

The view is a representation of a stale snapshot of your data. Consumers should not be expecting it to magically update -- if you want something more recent, go back to the repository for a new copy.

Upvotes: 4

Related Questions