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

EF Core query where sum of relationship is less than property

我必须 classes,一种产品 class 和一种跟踪订单的产品。两者都存储在数据库中,我使用 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 并在内存中执行查询,因为我的数据库很大。

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

你的意思是这样的吗?

您写道:

Get all Products where the sum of the Order.Quantity is less than the Product.AvailableQuantity and the Order.Confirmed property is 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);

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

如果您只想要已确认的,请考虑先使用 Select:

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

最后一点:你确定你的意思是小于 AvailableQuantity,而不是小于或等于: 如果有1个可用的产品,而您只需要发送一个,为什么不发送呢?