EF Core条件(添加)包括IQueryable

时间:2018-05-07 14:21:30

标签: c# entity-framework-core 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,因为它更安全'

第一行返回IIncludableQueryable<Order, User>,所以当我执行第二行“包含”时,它希望使其与众不同,例如IIncludableQueryable<Ordr,User,ProductOrder>

我大多数都有GetByIdWithCrudRelations,其中包含一组bool来选择要包含的内容和不包含的内容。有时它只有两个,但在这种情况下它有8个,这意味着如果我需要if-else的话,它可以有很多不同的结果。

任何人都有这个聪明的解决方案吗?

1 个答案:

答案 0 :(得分:5)

您可以使用完全相同的模式。只需从IQueryable<T>变量开始(请注意,IIncludableQueryable<T, P>仍然IQueryable<T>并支持其他ThenInclude),并使用ThenInclude代替嵌套Select

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