2011-10-28 110 views
12

我有1個類,我需要映射到多個類,例如。自動映射器映射到嵌套類

這是我從(視圖模型)映射來源:

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; } 
} 

這是目標類是如何(域模型):

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; } 

} 

這是怎麼了我的automapper創建地圖目前的樣子:

Mapper.CreateMap<UserBM, User>(); 

回答

22

定義兩個映射,從相同的源到不同的目的地都映射。在User映射,使用Mapper.Map<UserBM, Location>(...)

Mapper.CreateMap<UserBM, Location>(); 
Mapper.CreateMap<UserBM, User>() 
    .ForMember(dest => dest.Location, opt => 
     opt.MapFrom(src => Mapper.Map<UserBM, Location>(src)); 
+0

你怎麼能反其道而行之手動Location屬性映射? – xrklvs

+4

[SO]上有類似的線程(http://stackoverflow.com/questions/5984640/automapper-class-and-nested-class-map-to-one-class),我更喜歡映射的最後一個位:而不是'opt.MapFrom(src => Mapper.Map (src)',它使用更簡單的'opt => opt.MapFrom(src => src)' – superjos