0

The cast to value type 'System.Decimal' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.

public class Bar
{
    [Key]
    public int BarID { get; set; }
    public int Quantity { get; set; }
    public decimal? UnitTotal{get { return Quantity * (Pricelist == null ? 0 : Pricelist.Price); }}
    public decimal? DailyTotal { get; set; }
    public int PricelistID { get; set; }
    public virtual Pricelist Pricelist { get; set; }
}

bar.DailyTotal = db.Bars.Sum(h => h.Quantity * h.Pricelist.Price);
user2985240
  • 95
  • 2
  • 8
  • check this http://stackoverflow.com/questions/28265473/how-do-i-check-my-lambda-expression-for-null – GANI Jun 03 '15 at 00:29
  • http://stackoverflow.com/questions/6864311/the-cast-to-value-type-int32-failed-because-the-materialized-value-is-null – GANI Jun 03 '15 at 00:29
  • see this, it could be that your resultset is empty. http://stackoverflow.com/questions/2076827/linq-error-generic-parameter-or-the-query-must-use-a-nullable-type# – Arthur Russell Fox Dec 05 '16 at 06:21

3 Answers3

0

EDIT: It sounds like one of the mapped types is resolving as null. Such as the Quantity or Price fields.

Check the schema/mapping to make sure that if they are nullable they are mapped as a nullable type.

codemonkeh
  • 2,054
  • 1
  • 20
  • 36
0

To see where the problem comes from, try to use a foreach instead of that lambda expression.

decimal sum = 0;

foreach (var item in db.Bars)
{
    if (item.Pricelist != null && item.Pricelist.Price != null)
    {
        sum +=  item.Quantity * item.Pricelist.Price;
    }
    else
    {
        //Check this specific item from db.Bars which may have an inconsistent state
    }
}

Quantity is an non nullable int so basically i don't see it as the problem. So, the Pricelist may be the cause or its Price property which seems to be a nullable decimal.

Of course you can debug the lambda expression too but sometimes a detailed foreach is cleaner in my opinion.

Olaru Mircea
  • 2,570
  • 26
  • 49
0

If the calculating field is not nullable, then you need to cast nullable first for calculation. So the change will be like this below:

bar.DailyTotal = db.Bars.Sum(h => (decimal?) h.Quantity * h.Pricelist.Price) ?? 0m;

Also, add coalesce operator (??) to translate null to 0.

Rousonur Jaman
  • 1,183
  • 14
  • 19