0

我有以下代码:

    public ViewResult Stock(Guid id)
    {
        // Get the product form the database
        var product = productRepository.GetById(id);

        var viewModel = new ProductStockViewModel()
        {
            Product = product,
            ProductStoreStock = storeDB.Stores.Select(store => new ProductStoreStockViewModel()
            {
                Store = store,
                Bought = storeDB.Stocks
                    .Where(s => s.StoreId == store.StoreId)
                    .Where(p => p.ProductId == product.ProductId)
                    .Sum(s => s.Quantity),
                Sold = storeDB.OrderDetails
                    .Where(o => o.Order.StoreId == store.StoreId)
                    .Where(o => o.ProductId == product.ProductId)
                    .Sum(s => s.Quantity)
            })
            .ToList()
        };

        return View(viewModel);
    }

public class ProductStoreStockViewModel
{
    public Store Store { get; set; }
    //public Product Product { get; set; }

    public decimal Bought = 0;
    public decimal Sold = 0;

    public decimal Stock
    {
        get { return Bought - Sold; }
    }
}

我理解错误,有时产品已售出 0 次,因此 .Sum(s => s.Quantity) 返回空值。我知道我可以使用??0 如果满足该条件,但在 Linq 方法语法中表达该条件的最优雅方式是什么?

4

1 回答 1

0

您的问题可能是“storeDB.Stocks”为空或“storeDB.OrderDetails”为空(但在这里你会得到空执行)。以其他方式,您可以在查询中删除 1 where 以获得更优雅的代码,如下所示

Sold = storeDB.OrderDetails
                .Where(o => o.Order.StoreId == store.StoreId && o.ProductId == product.ProductId)
                .Sum(s => s.Quantity)

正如 Cédric Bignon 所说,如果查询为空但不为空,则“已售出”将为“0”。

于 2013-01-28T12:10:30.690 回答