TomSelleck
TomSelleck

Reputation: 6968

AutoMapper overwriting nested field with null

I have the following piece of code which should:

  1. Convert entity to dto
  2. Update property in dto
  3. Convert dto back to entity
  4. Update original entity with updated properties

This nearly works but during the final update - one of the fields is being set to null, but it should not be touched.

Main:

Entity e = new Entity("Id")
{
    Additional = new EntityAdditional()
    {
        Editable = "Change Me!",
        NotEditable = "Don't Change Me!"
    }
};

Dto dto = Mapper.Map<Dto>(e);

dto.Additional.Editable = "Changed!";

Mapper.Map<Dto, Entity>(dto, e); // e NotEditable is null!

Mapping:

config.CreateMap<Entity, Dto>()
    .ForMember(d => d.Additional,
    input => input.MapFrom(i => new DtoAdditional{
        Editable = i.Additional.Editable
    }));

config.CreateMap<Dto, Entity>()
    .ForMember(d => d.Additional,
    input => input.MapFrom(i => new EntityAdditional
    {
        Editable = i.Additional.Editable
    }));

Entity:

public class Entity
{
    public string Id { get; set; }
    public EntityAdditional Additional { get; set; }

    public Entity(string id) {
        Id = id;
        Additional = new EntityAdditional()
        {
            Editable = "Editable",
            NotEditable = "UnEditable"
        };
    }
}

public class EntityAdditional
{
    public string Editable { get; set; }
    public string NotEditable { get; set; }
}

Dto:

public class Dto
{
    public DtoAdditional Additional { get; set; }
}

public class DtoAdditional
{
    public string Editable { get; set; }
}

Upvotes: 0

Views: 56

Answers (1)

aaron
aaron

Reputation: 43128

That's because you specified:

new EntityAdditional
{
    Editable = i.Additional.Editable
//, NotEditable = null // Default value
}));

No need for custom mapping:

Mapper.CreateMap<EntityAdditional, DtoAdditional>()
    .ReverseMap();

Mapper.CreateMap<Entity, Dto>()
    .ReverseMap();

Upvotes: 1

Related Questions