gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 04:36:45 25 4
gpt4 key购买 nike

在 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> ,所以当我执行第二个 Include 时,它​​想让它变得不同,例如 IIncludableQueryable<Ordr,User,ProductOrder>

我主要有一个GetByIdWithCrudRelations其中包含一组 bool 值,用于选择包含哪些内容和不包含哪些内容。有时它只有两个,但在本例中它有 8 个,这意味着如果我需要 if-else 一切,它可能会产生很多不同的结果。

有人对此有聪明的解决方案吗?

最佳答案

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

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链不是嵌套的,不需要不同的变量名x , y , z等-单例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);

关于c# - EF Core 条件(添加)包含到 IQueryable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50216493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com