2011-10-28 5 views
12

私は、例えば、複数のクラスにマップする必要がある1つのクラスを持っています。Automapperはネストされたクラスにマップします

これは私が(ビューモデル)からのマッピングだソースです:

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

2つのマッピングを定義します。両方とも同じソースから別のデスティネーションにマッピングします。 Userマッピングでは、手動で反対のことを行うことができますどのように

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

Mapper.Map<UserBM, Location>(...)を使用して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

関連する問題