0

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?

4
  • configuration.AllowNullDestinationValues = true; Commented Mar 26, 2019 at 15:27
  • @LucianBargaoanu thanks - can you set that on individual mappings? Commented Mar 26, 2019 at 15:30
  • No, just globally or per profile. Commented Mar 26, 2019 at 15:45
  • But in 10.0 things changed: docs.automapper.org/en/latest/… Commented Aug 2, 2020 at 4:18

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.