简体   繁体   中英

How to solve the cast to value type 'System.Decimal' failure error

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

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM