Automapper unflatten with prefix

1.6k Views Asked by At

I have some DTOs which are mapped from Domain objects thanks to convention-based automapping, i.e. the Address fields are being flattened to the DTO.

This works fine for Domain -> DTO conversion, but the other way I have to "unflatten" the Address manually.

I wonder if there is a possibility to "prefix" the mapping configuration, so I could do something like

Mapper.CreateMap<PersonDTO, Address>().WithPrefix("Address");
...
Mapper.CreateMap<PersonDTO, Person>()
.ForMember(d => d.Address, opt => opt.MapFrom(src => Mapper.Map<Address>(src) ))

otherwise I have to manually map each Address field, which becomes the problem for more complex objects.

my domain objects and the DTO

class Person
{
    public string FirstName {get;set;}
    public string LastName {get;set;}
    public Address Address {get;set;}
}

class Address
{
    public string Street {get;set;}
    public string PostCode {get;set;}
}

and the following DTO:

class PersonDTO
{
    public string FirstName {get;set;}
    public string LastName {get;set;}
    public string AddressStreet {get;set;}
    public string AddressPostCode {get;set;}
}

edit

I'm aware of global configuration "recognized prefixes". I'd rather like to set obligatory prefix (not "one of the recognized") for the specific Map.

1

There are 1 best solutions below

0
On

Have a look at my answer on fllowing question: AutoMapper isn't recognizing profile-specific prefixes

Hope this helps!