The cast to value type 'Decimal' failed because the materialized value is null

1.9k Views Asked by At

I have the following code :

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

I understad the error, sometimes a product has been sold 0 times so .Sum(s => s.Quantity) returns a null value. I know I can use ?? 0 if that condition is meet but what's the most elegant way to express that in Linq method syntax?

1

There are 1 best solutions below

0
On

Your problem can be when 'storeDB.Stocks' is null or 'storeDB.OrderDetails' is null (but here you'll get null execption). In other way, you could remove 1 where in your query for more elegant code, like this

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

And as Cédric Bignon said 'Sold' will be '0' if query empty but not null.