我正在使用.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;
}
我错过了什么吗?这是一个错误吗?