I have 1 class that I need t map into multiple classes, for eg.
This is the source that I'm mapping from(view model):
public class UserBM
{
public int UserId { get; set; }
public string Address { get; set; }
public string Address2 { get; set; }
public string Address3 { get; set; }
public string State { get; set; }
public int CountryId { get; set; }
public string Country { get; set; }
}
This is how the destination class is(domain model):
public abstract class User
{
public int UserId { get; set; }
public virtual Location Location { get; set; }
public virtual int? LocationId { get; set; }
}
public class Location
{
public int LocationId { get; set; }
public string Address { get; set; }
public string Address2 { get; set; }
public string Address3 { get; set; }
public string State { get; set; }
public virtual int CountryId { get; set; }
public virtual Country Country { get; set; }
}
This is how my automapper create map currently looks:
Mapper.CreateMap<UserBM, User>();
I have another solution. The main idea is that AutoMapper know how to flatten nested objects when you name properly properties in flattened object: adding nested object property name as a prefix. For your case Location is prefix:
So creating familiar mapping from nested to flattened and then using ReverseMap method allows AutomMapper to understand how to unflatten nested object.
That's all!
Define two mappings, both mapping from the same source to different destinations. In the
User
mapping, map theLocation
property manually usingMapper.Map<UserBM, Location>(...)