Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Nullable object must have a value in Blazor

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,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading