[英]C# Entity Framework .ToList() on IQueryable throws an error System.Data.SqlTypes.SqlNullValueException: Data is Null
[英]Entity Framework Core throws System.Data.SqlTypes.SqlNullValueException when loading entities from DbContext
我在数据库中有这个 MyEntity 表:
MyEntity 中的数据如下:
EF Core 实体如下:
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.'
尝试从DbContext
加载MyEntity
时:
var myEntities = dbContext.Set<MyEntity>.ToList();
我究竟做错了什么?
您收到此错误是因为MyEntity
数据库表中的MyInt
为nullable
,并且您尝试加载的行之一的MyInt
设置为null
。
要解决此问题,只需将实体中的MyInt
属性的类型更改为Nullable<int>
或int?
:
public class MyEntity
{
public int Id { get; set; }
public int? MyInt { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.