繁体   English   中英

System.Data.SqlTypes.SqlNullValueException:数据为 Null。 无法对 Null 值调用此方法或属性

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

我正在升级到 Entity Framework Core 6.0.7,从我的数据库中读取时出现错误。 所有这些代码在升级之前都运行良好。

调用此方法时public virtual IQueryable<T> GetAll() => _dataContext.Set<T>(); 我收到以下错误

Microsoft.EntityFrameworkCore.Query[10100] 迭代上下文类型“Data.DbContext”的查询结果时发生异常。 System.Data.SqlTypes.SqlNullValueException:数据为 Null。 不能对 Null 值调用此方法或属性。

在这种情况下,通用类型<T>GameVariant class。

public class GameVariant : IEntityBase, IActiveEntity
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string IconUrl { get; set; }
    public bool Active { get; set; } = true;
}

查看我的GameVariant数据库表,我可以在其中看到很多记录。 但我注意到一些DescriptionIconUrl值是NULL 所以我将GameVariant class 上的DescriptionIconUrl属性更改为string? 而不是简单地string

现在,当调用GetAll()方法时,可以正常检索数据并且不再抛出错误。 谁能告诉我为什么将string更改为string? 解决这个问题? 我认为字符串默认可以为空?

另外,对于我来说,解决此问题的最佳方法是什么,而无需通过每个数据库 class 进行 go 并更新每个字符串属性?

从 C# 8.0 开始,引入了此更改。 简短的解释是这样的:

在 C# 8.0 之前,所有引用类型都可以为空。 可空引用类型是指 C# 8.0 中引入的一组功能,您可以使用这些功能来最大限度地降低代码导致运行时抛出 System.NullReferenceException 的可能性。 可空引用类型包括三个可帮助您避免这些异常的功能,包括将引用类型显式标记为可空的能力:

 - Improved static flow analysis that determines if a variable may be null before dereferencing it. - Attributes that annotate APIs so that the flow analysis determines null-state. - Variable annotations that developers use to explicitly declare the intended null-state for a variable.

对于冗长的解释检查: https://docs.microsoft.com/en-us/dotnet/csharp/nullable-references

您可以在项目级别禁用此功能,在.csproj 文件中添加以下内容:

<PropertyGroup>
  <Nullable>disable</Nullable>
</PropertyGroup>

您也可以检查此内容,但请注意,由于基于意见,它已关闭: 在 Net 6 的可空和实体框架实体中处理

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM