使用Null Propagation时出现NullReferenceException

时间:2018-05-27 10:06:02

标签: c# nullreferenceexception c#-6.0 null-propagation-operator

我正在使用 .NET Core 2.1.200 开发 ASP.NET Core MVC 应用程序。

我有一个响应模型和一个静态方法来从实体模型构建这个响应模型。

public static EntityTypeResponseModel FromEntityType(Entity.EntityType entityType)
{
    return new EntityTypeResponseModel
    {
        Id = entityType.Id,
        Name = entityType.Name,

        // NullReferenceException
        Fields = entityType.EntityTypeFields?.Select(x => FieldResponseModel.FromField(x.Field))
    };
}

虽然我使用了null传播,但是抛出了NullReferenceException。

执行传统的空检查可以解决问题:

public static EntityTypeResponseModel FromEntityType(Entity.EntityType entityType)
{
    var entityTypeResponseModel = new EntityTypeResponseModel
    {
        Id = entityType.Id,
        Name = entityType.Name
    };

    if (entityType.EntityTypeFields != null)
    {
        entityTypeResponseModel.Fields =
            entityType.EntityTypeFields?.Select(x => FieldResponseModel.FromField(x.Field));
    }

    return entityTypeResponseModel;
}

我错过了什么吗?这是一个错误吗?

1 个答案:

答案 0 :(得分:0)

这是我自己的错误。方法FieldResponseModel.FromField期望一个字段不能为空。

在实体中,我添加了实体(在通过我的控制器的编辑操作时)但是通过ID而不是通过实体对象。通过await _db.SaveChangesAsync()将此对象保存到db上下文后,ID属性的导航属性未自动设置(我期待的那样)。

我最终自己从db获取实体并设置实体对象。

// bad
junctionEntity.FieldId = 1

// good
junctionEntity.Field = await _db.Fields.SingleAsync(x => x.Id == 1)

这对我来说很有用,可能还有其他解决方案。