tinker
tinker

Reputation: 3424

How to do nested mapping with AutoMapper?

I have an entity and model defined as this:

public class User
{
    public int Id { get; set; }
    public string FirstName { get; set; }   
    public string LastName { get; set; }    
    public Location Location { get; set; }            
    public string Gender { get; set; }    
    public string Skills { get; set; }    
    public bool isPrivate { get; set; }
}

public class Location
{
    public int Id { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
}

public class UserModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Location Location { get; set; }
    public bool isPrivate { get; set; }
}

Then, I have setup a mapping profile defined as this:

public MappingProfile()
{
    CreateMap<User, UserModel>()
        .ReverseMap();
}

And the point is that this works to some extend, but the Location complex type is not mapped properly. I can always flatten it, by including LocationCity and LocationCountry inside the UserModel class, but that's not what I wanna do. I want Location to appear as a nested property in the returned result, as it is defined originally. How can I achieve this in AutoMapper?

Upvotes: 1

Views: 102

Answers (2)

nikifovadim
nikifovadim

Reputation: 135

You could define your configuration like this:

 CreateMap<User, UserModel>()
     .ForMember(um => um.Location , opt => opt.MapFrom(u => u.Location))
     .ReverseMap();

The ReverseMap can only create a simple mapping. For any complex type, you need to configure it manually, because AutoMaper don't know exactly how to instantiate the Location property and it will return null reference.

Upvotes: 0

CodeNotFound
CodeNotFound

Reputation: 23240

You need to add a mapping between Location to Location too. Yep, the source and destination are identitic.

So your mapping profile should look like this:

public MappingProfile()
{
    CreateMap<Location, Location>();
    CreateMap<User, UserModel>()
        .ReverseMap();
}

Upvotes: 1

Related Questions