1

嗯,我試圖將用戶配置文件模型映射到/從用戶配置文件viewmodel,但它不會工作,因爲它們不共享所有的數據字段:模型和視圖模型之間的AutoMapper錯誤:缺少類型映射配置或不支持的映射

型號:

public class UserProfile 
{ 
    public virtual string Id { get; set; } 
    public virtual string Interests { get; set; } 
    public virtual string Biography { get; set; } 
    public virtual string SmokingAttitude { get; set; } 
    public virtual string DrinkingAttitude { get; set; } 
    public virtual string Projects { get; set; } 
    public virtual string Groups { get; set; } 
} 

視圖模型:

public class UserProfileViewModel 
{ 
    [Display(Name = "Interests")] 
    public string Interests { get; set; } 

    [Display(Name = "Biography/Comments")] 
    public string Biography { get; set; } 

    [Display(Name = "Attitude to Smoking")] 
    public string SmokingAttitude { get; set; } 

    [Display(Name = "Attitude to Drinking")] 
    public string DrinkingAttitude { get; set; } 

    [Display(Name = "Projects working on")] 
    public string Projects { get; set; } 

    [Display(Name = "Groups joined")] 
    public string Groups { get; set; } 


    public IEnumerable<SelectListItem> AttitudeList 
    { 
     get 
     { 
      return new[]{ 
       new SelectListItem {Value = "not specified", Text = "not specified"}, 
       new SelectListItem {Value = "very negative", Text = "very negative"}, 
       new SelectListItem {Value = "negative", Text = "negative"}, 
       new SelectListItem {Value = "compromisable", Text = "compromisable"}, 
       new SelectListItem {Value = "neutral", Text = "neutral"}, 
       new SelectListItem {Value = "positive", Text = "positive"}, 
      }; 
     } 
    } 
} 

正如你可以看到,ID屬性被存儲在用戶簡檔模型(作爲密鑰來用戶表),但ñ在用戶配置文件viewmodel上。不過,用戶配置文件viewmodel具有爲選擇/下拉列表操作定義的額外字段AttitudeList。我認爲這是automapper無法正常工作的原因,但我完全無能爲力。

任何人都可以請幫忙嗎?這個想法很簡單,就是將通用字段從模型映射到視圖模型或從視圖模型映射出來,而忽略不同的字段。我希望我不必手動映射他們寫幾十行代碼...

回答

1

只是忽略該屬性。

Mapper.CreateMap<UserProfile, UserProfileViewModel>() 
     .Ignore(dst => dst.AttitudeList); 

Ignore mapping one property with Automapper

+0

我看到,它會工作,如果字段忽略的數量是1-2一樣漂亮,但仍然可以得到大而混亂,如果這兩個模型和視圖模型有2-3 +無與倫比的領域。有沒有辦法簡單地忽略任何不常見的字段?或者這是不可能的? – 2015-03-19 07:20:43

+0

http://stackoverflow.com/questions/954480/automapper-ignore-the-rest – VikciaR 2015-03-19 07:21:51

+0

或此:http://stackoverflow.com/questions/4367591/automapper-how-to-ignore-all-destination-members-除此之外的其他地方 – VikciaR 2015-03-19 07:22:17

相關問題