'My controller is throwing a 500 error even though I made sure to account for null values

I have the following block of code in my API Controller that is throwing a 500 error.

It says:

line 139

System.InvalidOperationException: Nullable object must have a value.
   at System.Nullable`1.get_Value()
   at PlantarySystemAPI.Controllers.Planet.PlanetarySatsController.PostNewMoon(SystemReference systemReference) in G:\Project\PlantarySystemAPI\API\Controllers\Planet\PlanetarySatsController.cs:line 139

In this block of code in the controller:

// line 139
if (planetSystem.HasMoon.Value && systemReference.HasMoon)
{
    return Conflict("System has no moon.");
}

However, I'm not sure why it's throwing that because I made sure to make planetSystem.HasMoon nullable like this:

public bool? HasMoon { get; set; }

And systemReference.HasMoon looks like this:

public bool HasMoon
{
    get
    {
        return SystemReference.Where(c => c.HasMoon == true).SingleOrDefault() != null;
    }
}

So I'm not sure why it's throwing the error.

Is there a better or proper way to check my values so I don't get this error?

Thanks!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source