Cul*_*tes 2 c# iqueryable entity-framework-core
在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));
}
Run Code Online (Sandbox Code Playgroud)
在EF Core中,无法覆盖,IQueryable因为它更“类型安全”
第一行返回一个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);
}
Run Code Online (Sandbox Code Playgroud)
注意,由于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);
Run Code Online (Sandbox Code Playgroud)