从DbContext加载实体时,实体框架核心会引发System.Data.SqlTypes.SqlNullValueException

时间:2020-05-26 05:59:02

标签: c# entity-framework entity-framework-core ef-core-2.2 ef-core-3.0

我在数据库中有这个MyEntity表:

MyEntity table in database

MyEntity中的数据如下:

Data in MyEntity table

EF核心实体如下:

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

我遇到一个例外:

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

尝试从MyEntity加载DbContext时:

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

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

由于出现以下错误,因为MyInt数据库表中的MyEntitynullable,并且您要加载的行之一将MyInt设置为null

要解决此问题,只需将您实体中的MyInt属性的类型更改为Nullable<int>int?

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