1
votes

According to Microsoft (https://docs.microsoft.com/en-us/dotnet/standard/microservices-architecture/microservice-ddd-cqrs-patterns/infrastructure-persistence-layer-implemenation-entity-framework-core) to encapsulate domain behavior private properties and readonly collections like this:

private readonly List<OrderItem> _orderItems; 
public IReadOnlyCollection<OrderItem> OrderItems => _orderItems;

And you can get the order with encapsulated order items like this:

public async Task<Order> GetAsync(int orderId)
    {
        var order= await _context.Orders.FindAsync(orderId);
        if (order != null)
        {
            await _context.Entry(order)
                .Collection(i => i.OrderItems)
                .LoadAsync();
        }

        return order;
    }

But what if the order items itself have encapsulated lists like following tree:
Supplier -> Catalogs -> CatalogItems
How do I get the CatalogItems collection as well?

1
With the usual EF Core Include / ThenInclude? There is nothing DDD specific. - Ivan Stoev
Ok. I just wondered if there is a variation of the Collection() method to accomplish this. - Palmi

1 Answers

1
votes

You can combine explicit loading methods Collection / Reference with eager loading methods Include / ThenInclude through Query method as partially shown in the Querying related entities section of the EF Core documentation.

For Supplier -> Catalogs -> CatalogItems example it could be like this:

public async Task<Supplier> GetAsync(int supplierId)
{
    var supplier = await _context.Suppliers.FindAsync(supplierId);
    if (supplier != null)
    {
        await _context.Entry(supplier)
            .Collection(e => e.Catalogs)
            .Query() // <--
            .Include(e => e.CatalogItems) // <--
            .LoadAsync();
    }
    return supplier;
}