Entity Framework Core throws System.Data.SqlTypes.SqlNullValueException when loading entities from DbContext

天涯浪子 提交于 2020-06-01 05:10:22

问题


I have this MyEntity table in the database:

The data inside MyEntity is the following:

The EF Core entity is the following:

public class MyEntity
{
    public int Id { get; set; }
    public int MyInt { get; set; }
}

I am getting an exception:

System.Data.SqlTypes.SqlNullValueException: 'Data is Null. This method or property cannot be called on Null values.'

when trying to load the MyEntity from the DbContext:

var myEntities = dbContext.Set<MyEntity>.ToList();

What am I doing wrong?


回答1:


You are getting this error because the MyInt in your MyEntity database table is nullable, and one of the rows you are trying to load has a MyInt set to null.

To fix this, just change the type of your MyInt property in your entity to Nullable<int> or int?:

public class MyEntity
{
    public int Id { get; set; }
    public int? MyInt { get; set; }
}


来源:https://stackoverflow.com/questions/62015584/entity-framework-core-throws-system-data-sqltypes-sqlnullvalueexception-when-loa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!