Last week I had the pleasure to work with a team that started using Entity Framework Core for the first time. They had a lot of experience using NHibernate, so the concept of an ORM was not new. But it was interesting to see which things are obvious when switching to EF Core and which are not.
I thought the team was finally on track after a few bumps in the road when they came back to me with another problem.
When trying to fetch a set of entities, the query failed with the following error message:
System.Data.SqlTypes.SqlNullValueException : Data is Null. This method or property cannot be called on Null values.
This was the object they were trying to fetch:
And here is the LINQ query they were using:
I have to admit that it took me a while before I discovered why this failed.
The reason becomes obvious if you take a look inside the csproj file:
This project had Nullable Reference Types enabled. If this is enabled and you have a required property that shouldn’t be null, EF Core will throw the error above when the database query returns a NULL value.
The solution was to mark the correct properties as nullable inside the entity class:
More information
Working with nullable reference types - EF Core | Microsoft Learn