Entity Framework Core: `SqlNullValueException: Data is Null.` How to troubleshoot?
The error message indicates that EF Core is trying to read string
value for a required property, i.e. a property which should never has null
value in the database, but instead the underlying data reader reports null
value for that property in some record{s).
Looking at your entity model and corresponding database table, you can see the obvious discrepancy for many string
properties -> varchar
columns. CompanyStreetAddress
, CompanyCity
, CompanyZipCode
, CompanyVatNumber
, ContactFirstName
, ContactLastName
- all these are marked as [Required]
in the model, bit have no corresponding not null
constraint in the table.
So the problem is caused by one or more of these columns.
You need to fix that discrepancy - probably by removing [Required]
attribute because the constraint is already broken in the existing data.
The fact that it "works" in some older EF Core version doesn't matter - that's incorrect mapping and as such should be fixed. Technically it shouldn't worked from the beginning. But remember that EF Core is still in active development and has many bugs which are fixed in the next release(s). Most likely some code change was made between "working" and "non working" EF Core version which fixes the previous incorrect behavior.
If you are trying to read some nullable data from the database, but your type is not nullable you can get this error.
If MyInt
is nullable in the database and you have this entity:
public class MyEntity
{
public int Id { get; set; }
public int MyInt { get; set; }
}
You will get the exception: System.Data.SqlTypes.SqlNullValueException: 'Data is Null. This method or property cannot be called on Null values.'
To fix this, just change the type of your MyInt
property to Nullable<int>
or int?
:
public class MyEntity
{
public int Id { get; set; }
public int? MyInt { get; set; }
}
Note: This is not an answer to the original question, but is an answer to the question in the title.
This kind of exception can also appear if you enable latest Nullable feature from C# 8.
EF Core, at least currently, it's not fully compatible with C# 8 nullable types. So for example, given that you enable the Nullable feature for the project, if you have a type like this:
public class MyEntity
{
public string MyProperty { get; set; }
}
even if the property it's not marked with the [Required] attribute, EF core raise this kind of exception because it requires that value in database it's not null (i.e. it doesn't test the column value with IsDbNull).
For further info on how to handle nullable reference types in EF core take a look at: https://docs.microsoft.com/en-us/ef/core/miscellaneous/nullable-reference-types