In this article I will explain with an example, how to resolve the error:
Data is Null. This method or property cannot be called on Null values in
ASP.Net.
Error
The following error occurs when there is NULL data in your Database table.
Solution
The solution to this problem is to make the properties in the Model class Nullable so that they allow NULL values by simply adding a ‘?’ as shown below.
Here, City and Country columns have NULL values and hence only those properties were made Nullable.
public class Customer
{
public string CustomerID { get; set; }
public string ContactName { get; set; }
public string? City { get; set; }
public string? Country { get; set; }
}
If you are unable to determine which property will have NULL values, then you can make all the properties Nullable as shown below.
public class Customer
{
public string? CustomerID { get; set; }
public string? ContactName { get; set; }
public string? City { get; set; }
public string? Country { get; set; }
}