Search code examples
c#nullreferenceexceptionc#-6.0null-propagation-operator

NullReferenceException while using Null Propagation


I am working on a ASP.NET Core MVC Application with .NET Core 2.1.200.

I have a response model and a static method to build this response model from the entity model.

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))
    };
}

Although I use null propagation a NullReferenceException is thrown.

Doing a traditional null check fixes the issue:

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;
}

Am I missing something? Is this a bug?


Solution

  • This was a mistake from myself. The method FieldResponseModel.FromField expected a field which must not be null.

    In the entity, I added entities (while going through the edit action of my controller) but via ID and not via entity object. After saving this object into the db context via await _db.SaveChangesAsync() the navigation property of the ID-property did not automatically set (which I was expecting).

    I ended up getting the entity from the db myself and set the entity object.

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

    This works for me, there may be other solutions out there.