关系总和小于属性的 EF Core 查询



我必须上课,一个产品类和一个跟踪订单的产品类。两者都存储在数据库中,我使用 ef core 作为 orm。

public class Product
{
public int Id { get; set; }
public int AvailableQuantity { get; set; }
public ICollection<Order> Orders { get; set; }
}
public class Order
{
public int Id { get; set; }
public bool Confirmed { get; set; }
public int Quantity { get; set; }
public int ProductId { get; set; }
public Product Product { get; set; }
}

现在我需要获取Order.Quantity之和小于Product.AvailableQuantityOrder.Confirmed属性为真的所有产品。

我已经试过了

_context.Products.Where(product => product.Orders.Where(order => order.Confirmed).Sum(order => order.Quantity) < product.AvailableQuantity)

但这显然行不通。我猜我需要一些GroupBy的东西,但我无法弄清楚如何让这个查询工作。 我也不想使用AsEnumerable并在内存中执行查询,因为我的数据库很大。

你写道:

获取"订单.数量">

之和小于"产品.可用数量"和"订单.已确认"属性为 true 的所有产品。

我想你的意思是说:

要求:获取所有产品及其已确认订单,其中这些已确认订单的数量之和小于产品的可用数量。

如果您可能还希望在最终结果中包含未确认的订单。这不会改变太多。

var result = dbContext.Products.Where(product =>
// keep only the Products where the sum of the confirmed orders is less than ...
product.Orders.Where(order => order.Confirmed)
.Select(order => order.Quantity)
.Sum() < product.AvailableQuantity);

这将为您提供产品及其所有订单:已确认的和未确认的。

如果只想要已确认的,请考虑先使用"选择":

var productsThatCanBeDelivered = dbContext.Products.Select(product => new
{
// Select only the product properties that you plan to use:
Id = product.Id,
AvailableQuantity = product.AvailableQuantity,
ConfirmedOrders = product.Orders
.Where(order => order.Confirmed)
.Select(order => new
{
// select only the order properties that you plan to use
Id = order.Id,
Quantity = order.Quantity,
...
// no need for this: you already know the value
// ProductId = order.ProductId,
// Confirmed = order.Confirmed,
})
.ToList(),
})
// keep only those Products where the quantities of the confirmed orders is less than ...
.Where(product => product.ConfirmedOrders
.Select(confiredOrder => confirmedOrder.Quantity)
.Sum() < product.AvailableQuantity);

最后一句话:你确定你的意思是小于可用数量,而不是小于或等于: 如果有 1 个可用产品,而您只需要交付一个,为什么不交付它?

_context.Orders.Where(c => c.Confirmed).AsQueryable().GroupBy(c => c.ProductId)
.Where(c => c.Sum(d => d.Quantity) < c.First().Product.AvailableQuantity)
.ToDictionary(c => c.Key, c => c);

你的意思是这样吗?

最新更新