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:
public class Customer : Entity<string> | |
{ | |
protected Customer() | |
{ | |
} | |
public Customer(string customerID) | |
{ | |
this.Id = customerID; | |
} | |
public string Address { get; set; } | |
public string City { get; set; } | |
public string CompanyName { get; set; } | |
public string ContactName { get; set; } | |
public string ContactTitle { get; set; } | |
public string Country { get; set; } | |
public string Fax { get; set; } | |
public string Phone { get; set; } | |
public string PostalCode { get; set; } | |
public string Region { get; set; } | |
} |
And here is the LINQ query they were using:
public async Task<IList<Customer>> FindByCountry(string countryName) | |
{ | |
return await _context.Customers.Where(c => c.Country == countryName).ToListAsync(); | |
} |
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:
<Project Sdk="Microsoft.NET.Sdk"> | |
<PropertyGroup> | |
<TargetFramework>net7.0</TargetFramework> | |
<ImplicitUsings>enable</ImplicitUsings> | |
<Nullable>enable</Nullable> | |
</PropertyGroup> | |
</Project> |
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:
public class Customer : Entity<string> | |
{ | |
protected Customer() | |
{ | |
} | |
public Customer(string customerID) | |
{ | |
this.Id = customerID; | |
} | |
public string? Address { get; set; } | |
public string? City { get; set; } | |
public string CompanyName { get; set; } | |
public string? ContactName { get; set; } | |
public string? ContactTitle { get; set; } | |
public string? Country { get; set; } | |
public string? Fax { get; set; } | |
public string? Phone { get; set; } | |
public string? PostalCode { get; set; } | |
public string? Region { get; set; } | |
} |
More information
Working with nullable reference types - EF Core | Microsoft Learn