转换为值类型'Decimal'失败,因为具体化值为null

时间:2013-01-28 11:29:34

标签: 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,
            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方法语法中表达它的最优雅方式是什么?

1 个答案:

答案 0 :(得分:0)

你的问题可能是'storeDB.Stocks'为null或'storeDB.OrderDetails'为null(但在这里你会得到null execption)。换句话说,您可以在查询中删除1个更优雅的代码,例如

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

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