efcore: Getting SqlNullValueException after upgrading to .Net Core 2.2
I was using .Net Core 2.1 and everything was fine. I just upgraded to .Net Core 2.2, and have started to see the following error: “SqlNullValueException: Data is Null. This method or property cannot be called on Null values.” My code lines are:
var sl = _context.Assets.OrderBy(e => e.Name); var slCnt = sl.Count(); var selectlist = new SelectList(sl, "AssetId", "Name").ToList();
On hitting the last of the 3 statements above, the code breaks with the said error. The ‘sl’ object is created, and I can get the count from the first two statements. Also, both AssetId and Name are non-null fields in the database, and I have checked to confirm that there is no null value in either column.
I should point out that all other SelectLists (for the other entities) work well even in 2.2. I am just not sure what is different with the Assets entity which has not changed since upgrading to 2.2.
Further technical details
EF Core version: 2.2 Database Provider: Microsoft.EntityFrameworkCore.SqlServer Operating system: Windows 10 IDE: Visual Studio 2017 15.9.5
About this issue
- Original URL
- State: closed
- Created 5 years ago
- Comments: 17 (7 by maintainers)
Also, EF can be configured (in
OnModelCreating
) to ignore theRequired
attribute and allow nulls.I’ve experienced this issue when going from .NET Core 2.2 to 3-preview5 and it was caused by the fact I had abstract Entity class that contained
[Required]
attribute onnullable
property. I would assume that same thing can happen if you configure required property via fluent API..Net Core 2.2 didn’t seem to care and it worked perfectly fine, but the correct behavior is the one implemented in .NET Core 3 and this has admittedly been my mistake.
For reference I had something like:
That is incorrect conclusion. You can put
Required
attribute as needed but when reading value of such column from database it has to have a value. If it has null, it will throw exception. i.e. if data in database does not match the validation attributes you use then it is error.This error happens when materializing query results is expecting non-null values but the value in results in database contains NULL. The cause of error could be bad data, incorrect model or bug in query pipeline to infer the type nullability correctly. Without a repro project we cannot determine the cause. Please post a runnable project which demonstrate the issue.