0
votes

I've set up my Automapper config and it's fine when mapping from Entities onto Dtos. However, when I try to map from a Dto back to an Entity, it populates all the virtual properties of the Entity with empty data, causing new objects to be created.

Psuedocode which should demonstrate the problem:

public class MyEntity
{
    public string MyString { get; set; }

    public virtual MyOtherEntity MyOtherEntity
}

public class MyEntityDto
{
    public string MyString { get; set; }

    public virtual MyOtherEntityDto MyOtherEntity
}

config.CreateMap<MyEntity, MyEntityDto>()
    .ForSourceMember(obs => obs.MyOtherEntity, dto => dto.DoNotValidate())
    .ReverseMap();


// using this to create an Entity creates an empty MyOtherEntity object on it
var entity = Mapper.Map<MyEntityDto, MyEntity>(myEntityDto);
_context.MyEntities.Add(entity);

// so this tries to create a new MyOtherEntity in the db
_context.SaveChanges();

I can get around this by creating the entity manually, but is there not a way to set up Automapper to leave these properties empty?

1
configuration.AllowNullDestinationValues = true; - Lucian Bargaoanu
@LucianBargaoanu thanks - can you set that on individual mappings? - Bob Tway
No, just globally or per profile. - Lucian Bargaoanu
But in 10.0 things changed: docs.automapper.org/en/latest/… - Lucian Bargaoanu

1 Answers

1
votes

For ReverseMap() AutoMapper creates a reverse mapping configuration that includes unflattening which results with creating new object for virtual property. You can remove the call to ReverseMap() and create two separate maps or, you can use Ignore.

https://docs.automapper.org/en/stable/Reverse-Mapping-and-Unflattening.html