Home > database >  Nullable object must have a value in Blazor
Nullable object must have a value in Blazor

Time:09-22

I am trying to do a calculation among a few columns in my database table. I have attached the model for reference:

public partial class CarSalesTable
    {
        public int CarSalesTableId { get; set; }
        public string? CarName{ get; set; }
        public decimal? Price{ get; set; }
        public decimal? Month1Sales{ get; set; }
        public decimal? Month2Sales{ get; set; }
        public decimal? TotalSales{ get; set; }
    }

I am testing a basic calculation that I want to apply to my TotalSales field where I want to take Month1Sales and add it to Month2Sales. Here is my code block for that,

 @{
    decimal Total = (decimal)@context.Month1Sales (decimal)@context.Month2Sales;
    Math.Round(Total, 3);
  }

I am then assigning that value to my table row for TotalSales,

<MudTd DataLabel="Total"  >@Math.Round(TotalSales,3)</MudTd>

the project builds and runs until you open the page where this data would sit, then it throws a Nullable object must have a value error. Could someone explain to me what I am doing wrong. I have seen other posts of this error but none like this and I am confused

CodePudding user response:

These values are nullable:

public decimal? Month1Sales{ get; set; }
public decimal? Month2Sales{ get; set; }

But you are forcibly casting to a non-nullable value:

(decimal)@context.Month1Sales (decimal)@context.Month2Sales

What happens when they are null? A decimal can't be null, so this will fail.

Instead of directly casting, you can use null coalescing to default to 0 for your calculation when the value is null. For example:

decimal Total = (context.Month1Sales ?? 0)   (context.Month2Sales ?? 0);

This would effectively treat null and 0 the same in your calculations.

  • Related