I have multiple classes that I need to map into 1 class:
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>();
Based on the documents on automapper codeplex site, this should be automatic but it doesn’t work. Address, Address2, etc is still null. What should my createmap look like?
The reason is because AutoMapper can’t map all those flat fields to a
Locationobject by convention.You’ll need a custom resolver.
However, i dont like this. IMO, a better way would be to encapsulate those properties in your ViewModel into a nested viewmodel:
Then all you have to do is define an additional map:
Then it will all work.
You should try and make use of AutoMapper conventions, where possible. And it’s certainly possible to make your ViewModel more hierachical, to match the destinations hierachy.