AutoMap a property to property of sub-property

2019-07-29 04:36发布

问题:

I have this simple data model:

// Model
public class Address
{
    public string Street { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string ZipCode { get; set; }
    .... Another values here ....
}

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Address Address { get; set; }
    .... Another values here ....
}

// ViewModel
public class PersonViewModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Street { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string ZipCode { get; set; }
}

I want to map (using AutoMapper) the values of PersonViewModel to the corresponding properties (where AutoMapper discovers if the property should be in the root object or inside the sub-object). Keeping in mind, AutoMapper should not create neither Person object nor Address (the objects must be created manually to fill another properties before auto mapping), and AutoMapper uses the already existed objects. For example:

var addressObj = new Address
{

    ... Filling some values...

};
var personObj = new Person
{

    Address = addressObj;
    ... Filling some values...

};

mapper.Map(personViewModelObj, personObj); // How to make this work for both Person and Address properties?

How can I get that auto mapping to work for both person properties and address properties?

Should I add two mapping rules (for address and for person), and execute mapper.Map() twice?

回答1:

Using @Jasen comments I got it working. The main problem was that I am mapping in a reversed direction. This sentence in official documentation solves the problem:

Unflattening is only configured for ReverseMap. If you want unflattening, you must configure Entity -> Dto then call ReverseMap to create an unflattening type map configuration from the Dto -> Entity.

Here is the link:

https://github.com/AutoMapper/AutoMapper/blob/master/docs/Reverse-Mapping-and-Unflattening.md

In other words, to get unflattering to work, I have (or must) to map in this direction:

CreateMap<HierarchicalObject, FlattenedObject>()
    .ReverseMap();