EF Core:如何访问多层封装集合

时间:2018-03-27 17:47:16

标签: c# entity-framework-core

根据Microsoft(https://docs.microsoft.com/en-us/dotnet/standard/microservices-architecture/microservice-ddd-cqrs-patterns/infrastructure-persistence-layer-implemenation-entity-framework-core)封装域行为私有属性和readonly集合,如下所示:

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

您可以使用这样的封装订单商品获取订单:

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;
    }

但是,如果订单商品本身已经封装了如下列树的列表,那该怎么办呢? 供应商 - &gt;目录 - &gt; CatalogItems
我如何获得CatalogItems集合?

1 个答案:

答案 0 :(得分:1)

您可以将explicit loading methods Collection / Referenceeager loading方法Include / ThenInclude合并到Query方法,部分显示在EF Core文档的Querying related entities部分中。

供应商 - &gt;目录 - &gt; CatalogItems示例可能是这样的:

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;
}