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?
configuration.AllowNullDestinationValues = true;