简体   繁体   English

EF Core 无法加载具有可为空字符串值的实体

[英]EF Core fail to load entity with nullable string value

I am having an issue retrieving any records which have a null string value from the database.我在从数据库中检索具有 null 字符串值的任何记录时遇到问题。 I am using SQL Server 2012, .NET 5.0.我正在使用 SQL 服务器 2012、.NET 5.0。

My model class:我的 model class:

public class Project
{
    public int ProjectId { get; set; }

    [StringLength(50)]
    public string ProjectSaleTypeId { get; set; }

    [JsonIgnore]
    public ProjectSaleType ProjectSaleType { get; set; }
}

public class ProjectSaleType
{

    [StringLength(50)]
    public string ProjectSaleTypeId { get; set; }

    [JsonIgnore]
    public ICollection<Project> Projects { get; set; }
}

Then when I make a request to get the entity with id 365 :然后,当我请求获取 id 为365的实体时:

_context.Projects.FirstOrDefault(x => x.ProjectId == 365);

the following error occurs:出现以下错误:

System.InvalidOperationException: 'An error occurred while reading a database value for property 'Project.ProjectSaleTypeId'. System.InvalidOperationException:'读取属性'Project.ProjectSaleTypeId'的数据库值时发生错误。 The expected type was 'System.String' but the actual value was null.'预期类型为“System.String”,但实际值为 null。

It should be noted that entities which have a ProjectSaleTypeId are working properly.应该注意的是,具有ProjectSaleTypeId的实体工作正常。

I understand that C# 8.0 introduced nullable reference types.我了解 C# 8.0 引入了可为空的引用类型。 But I have not enabled these in my project;但是我没有在我的项目中启用这些; https://docs.microsoft.com/en-us/ef/core/miscellaneous/nullable-reference-types https://docs.microsoft.com/en-us/ef/core/miscellaneous/nullable-reference-types

Why do I get this error when retrieving a entity with the ProjectSaleTypeId equal to null?为什么在检索ProjectSaleTypeId等于 null 的实体时会出现此错误?

This error means that the ProjectSaleTypeId is a non-nullable string property but your database table is allowing NULL values for that column.此错误意味着 ProjectSaleTypeId 是不可为空的字符串属性,但您的数据库表允许该列的 NULL 值。

If EF is handling your database it should not happen, but it might occur that you accidentally changed the DB column type and didn't migrate properly.如果 EF 正在处理您的数据库,则不应该发生这种情况,但您可能会意外更改 DB 列类型并且没有正确迁移。

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

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