EF Core 条件(添加)包含到 IQueryable

EF Core conditional (add) includes to an IQueryable

在 EF6 中我习惯这样做:

var orders = GetAllEntities().Include(x => x.Contact.User);
if (includeProducts)
{
    orders = orders.Include(x => x.ProductOrders.Select(y => y.RentStockOrders));
    orders = orders.Include(x => x.ProductOrders.Select(y => y.Product));
    orders = orders.Include(x => x.ProductOrders.Select(y => y.Currency));
    orders = orders.Include(x => x.ProductOrders.Select(y => y.Coupons));
    orders = orders.Include(x => x.AdditionalCosts);
    orders = orders.Include(x => x.Partner);
    orders = orders.Include(x => x.OrderCoupons.Select(y => y.Coupon.Partner));
    if (includeStock)
    {
        orders = orders.Include(x => x.ProductOrders.Select(y => y.RentStockOrders.Select(z => z.Stock)));
    }
}
if (includeInvoices)
{
    orders = orders.Include(x => x.Invoices.Select(y => y.Attachments));
}

在 EF Core 中无法覆盖 IQueryable 因为它比 'typesafe'

第一行returns一个IIncludableQueryable<Order, User>,所以当我做第二个Include的时候,它想让它变得不一样,比如IIncludableQueryable<Ordr,User,ProductOrder>

我主要有一个 GetByIdWithCrudRelations,其中包含一组布尔值,用于选择要包含的内容和不包含的内容。有时它只有两个,但在这种情况下它有 8 个,这意味着如果我需要 if-else 一切,它可以有很多不同的结果。

有人对此有巧妙的解决方案吗?

您可以使用完全相同的模式。只需从 IQueryable<T> 变量开始(请注意,IIncludableQueryable<T, P> 仍然是 IQueryable<T> 并具有额外的 ThenInclude 支持)并使用 ThenInclude 而不是嵌套的 Selects:

IQueryable<Order> orders = GetAllEntities().Include(x => x.Contact.User);
// or var orders = GetAllEntities().Include(x => x.Contact.User).AsQueryable();
if (includeProducts)
{
    orders = orders.Include(x => x.ProductOrders).ThenInclude(y => y.RentStockOrders);
    orders = orders.Include(x => x.ProductOrders).ThenInclude(y => y.Product);
    orders = orders.Include(x => x.ProductOrders).ThenInclude(y => y.Currency);
    orders = orders.Include(x => x.ProductOrders).ThenInclude(y => y.Coupons);
    orders = orders.Include(x => x.AdditionalCosts);
    orders = orders.Include(x => x.Partner);
    orders = orders.Include(x => x.OrderCoupons).ThenInclude(y => y.Coupon.Partner);
    if (includeStock)
    {
        orders = orders.Include(x => x.ProductOrders).ThenInclude(y => y.RentStockOrders).ThenInclude(z => z.Stock);
    }
}
if (includeInvoices)
{
    orders = orders.Include(x => x.Invoices).ThenInclude(y => y.Attachments);
}

请注意,由于 ThenInclude 链没有嵌套,因此不需要不同的变量名称 xyz 等 - 单个 x 或类似的会做同样的事情。

此外,由于 Include 从根重新启动包含链,因此可以组合 orders = orders.Include(...) 等非条件赋值,例如

orders = orders
    .Include(x => x.ProductOrders).ThenInclude(y => y.RentStockOrders)
    .Include(x => x.ProductOrders).ThenInclude(y => y.Product)
    .Include(x => x.ProductOrders).ThenInclude(y => y.Currency)
    .Include(x => x.ProductOrders).ThenInclude(y => y.Coupons)
    .Include(x => x.AdditionalCosts)
    .Include(x => x.Partner)
    .Include(x => x.OrderCoupons).ThenInclude(y => y.Coupon.Partner);