0

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

Kibofigs
  • 15
  • 6
  • Why are you casting to a decimal? It's already a (nullable) decimal. Are you checking that the value is not null before using it? Where are you setting those properties? – gunr2171 Sep 21 '22 at 14:27
  • Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – gunr2171 Sep 21 '22 at 14:28

1 Answers1

1

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.

David
  • 208,112
  • 36
  • 198
  • 279
  • That works! I did not understand how that worked... the error wording confused me... Nullable object must have a value, but its nullable :( – Kibofigs Sep 21 '22 at 14:36
  • 1
    @Kibofigs: Error messages like that can be a bit ambiguous. I've worked with non-native English speakers who get confused by that sometimes. It's not indicating that the nullable object *itself* "must have a value", but that it "must have a value" in order to be used the way it's being used but currently "doesn't have a value". – David Sep 21 '22 at 14:37