我有以下代码:
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 方法语法中表达该条件的最优雅方式是什么?
你的问题可能是当"storeDB.Stocks"为空或"storeDB.OrderDetails"为空时(但在这里你会得到空执行)。换句话说,您可以在查询中删除 1 的位置以获得更优雅的代码,如下所示
Sold = storeDB.OrderDetails
.Where(o => o.Order.StoreId == store.StoreId && o.ProductId == product.ProductId)
.Sum(s => s.Quantity)
正如塞德里克·比尼翁所说,如果查询为空但不为空,则"已售出"将为"0"。