2014-10-30 102 views
2

我試圖讓AutoMapper工作,並且真的陷入了一個簡單的任務。我在用戶實體定義的複雜類型:Automapper,複雜的屬性和繼承

[ComplexType] 
public class CustomerProfile 
{ 
    public string  FirstName    { get; set; } 
    public string  LastName     { get; set; } 
    // ... 
} 

public class User 
{ 
    public long Id {get; set;} 
    public string Email { get; get; } 
    public CustomerProfile CustomerProfile { get; set; } 
} 

我有這樣的視圖模型:

public class CustomerViewModel : CustomerProfile 
{ 
    public string Email { get; set; } 
} 

所以我只是有所有的CustomerProfile性質的視圖模型以及電子郵件。

我想將用戶映射到CustomerViewModel。我嘗試了一切,但實際上並沒有成功。即使此代碼不起作用:

Mapper.CreateMap<CustomerProfile, CustomerViewModel>(); 

Automapper只是拒絕映射任何東西。

它如何映射?謝謝。

+2

是什麼那「不起作用」,它不起作用? – Default 2014-10-30 12:27:26

回答

2

您可以使用.ConstructUsingUser實例創建CustomerViewModel。然後將剩餘的性質(例如,Email)將由AutoMapper自動映射只要名稱匹配:

Mapper.CreateMap<CustomerProfile, CustomerViewModel>(); 

Mapper.CreateMap<User, CustomerViewModel>() 
    .ConstructUsing(src => Mapper.Map<CustomerViewModel>(src.CustomerProfile)); 

實施例:https://dotnetfiddle.net/RzpD4z


更新

爲了使AssertConfigurationIsValid()通過,您需要忽略手動映射的屬性。您還需要忽略來自CustomerProfileCustomerViewModel映射上CustomerViewModelEmail財產,因爲這將由UserCustomerViewModel映射照顧:

Mapper.CreateMap<CustomerProfile, CustomerViewModel>() 
    // Ignore Email since it's mapped by the User to CustomerViewModel mapping. 
    .ForMember(dest => dest.Email, opt => opt.Ignore()); 

Mapper.CreateMap<User, CustomerViewModel>() 
    .ConstructUsing(src => Mapper.Map<CustomerViewModel>(src.CustomerProfile)) 
    // Ignore FirstName/LastName since they're mapped above using ConstructUsing. 
    .ForMember(dest => dest.FirstName, opt => opt.Ignore()) 
    .ForMember(dest => dest.LastName, opt => opt.Ignore()); 

更新例如:https://dotnetfiddle.net/KitDiC

+0

順便說一句,你知道爲什麼這不起作用:https://dotnetfiddle.net/hXlNKY – 2014-10-31 07:32:07

+0

@羅曼普希金:是的,你需要忽略你用'ConstructUsing'調用映射的屬性。感謝您指出,我會更新我的答案。 – 2014-10-31 13:07:49