Linq 转换为值类型';十进制';由于物化值为null,因此失败
我有以下代码:Linq 转换为值类型';十进制';由于物化值为null,因此失败,linq,linq-method-syntax,Linq,Linq Method Syntax,我有以下代码: public ViewResult Stock(Guid id) { // Get the product form the database var product = productRepository.GetById(id); var viewModel = new ProductStockViewModel() { Product = product,
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”为null或“storeDB.OrderDetails”为null时,您可能会遇到问题(但这里您将得到null execption)。换句话说,您可以删除查询中的1 where以获得更优雅的代码,如下所示
Sold = storeDB.OrderDetails
.Where(o => o.Order.StoreId == store.StoreId && o.ProductId == product.ProductId)
.Sum(s => s.Quantity)
正如塞德里克·比格农(Cédric Bignon)所说,如果查询为空但不为null,则“sell”将为“0”。您的问题不是直接来自Sum中的0个元素(如果源代码不包含元素,Sum(IEnumerable)方法将返回零。)。在
null
和0
之间有很大的区别。你的问题是前者,而不是后者。