从DbContext加载实体时,实体框架核心会引发System.Data.SqlTypes.SqlNullValueException [英] Entity Framework Core throws System.Data.SqlTypes.SqlNullValueException when loading entities from DbContext

查看:94
本文介绍了从DbContext加载实体时,实体框架核心会引发System.Data.SqlTypes.SqlNullValueException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have this MyEntity table in the database:

MyEntity中的数据如下:

The data inside MyEntity is the following:

EF核心实体如下:

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

我遇到了一个例外:


System.Data.SqlTypes.SqlNullValueException:'数据为空。不能在Null值上调用此方法或属性。'

尝试加载<$ c时来自 DbContext 的$ c> MyEntity :

when trying to load the MyEntity from the DbContext:

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

我在做什么错了?

推荐答案

您收到此错误,因为 MyEntity 数据库表中的 MyInt nullable ,并且您要加载的行之一将 MyInt 设置为 null

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.

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

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; }
}

这篇关于从DbContext加载实体时,实体框架核心会引发System.Data.SqlTypes.SqlNullValueException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆