2

我正在使用.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))
    };
}

尽管我使用空传播,但会引发 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;
}

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

4

1 回答 1

0

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

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

我最终自己从数据库中获取了实体并设置了实体对象。

// bad
junctionEntity.FieldId = 1

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

对我有用,可能还有其他解决方案。

于 2018-05-27T10:15:54.483 回答