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?
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
And as Cédric Bignon said 'Sold' will be '0' if query empty but not null.