2016-06-29 30 views
1

我有一個模型類:映射列表<Model>到詞典<INT,視圖模型>

public class Model { 
    public int Id {get;set;} 
    public string Name {get;set;} 
} 

和視圖模型:

public class ViewModel { 
    public string Name {get;set;} 
} 

欲列表映射到字典其中鍵將Model.Id。

我已經開始用這樣的配置:

configuration 
    .CreateMap<Model, KeyValuePair<int, ViewModel>>() 
    .ConstructUsing(
     x => 
      new KeyValuePair<int, ViewModel>(x.Id, _mapper.Map<ViewModel>(x))); 

但我不希望在配置中使用映射器實例。有沒有其他方法可以實現這一目標?我見過一些答案,人們使用x.MapTo(),但似乎並沒有提供了...

回答

0

由@hazevich提供的解決方案在5.0更新後停止工作。這是可行的解決方案。


你需要創建一個類型轉換器:

public class ToDictionaryConverter : ITypeConverter<Model, KeyValuePair<int, ViewModel>> 
{ 
    public KeyValuePair<int, ViewModel> Convert(Model source, KeyValuePair<int, ViewModel> destination, ResolutionContext context) 
    { 
     return new KeyValuePair<int, ViewModel>(source.Id, context.Mapper.Map<ViewModel>(source)); 
    } 
} 

,然後在配置中使用它:

configuration 
    .CreateMap<Model, KeyValuePair<int, ViewModel>>() 
    .ConvertUsing<ToDictionaryConverter>(); 
1

您可以使用映射例如從拉姆達參數x.Engine.Mapper

簡單,因爲這

configuration 
    .CreateMap<Model, KeyValuePair<int, ViewModel>>() 
    .ConstructUsing(context => new KeyValuePair<int, ViewModel>(
     ((Model)context.SourceValue).Id, 
     context.Engine.Mapper.Map<ViewModel>(context.SourceValue))); 
+0

謝謝 - 看起來不錯,但我想我錯過了一些參考 - 編譯期間出現錯誤(即使IntelliSense正常工作): 'ResolutionContext'不包含'Id'的定義,而 'QuotationPosition'不包含'Engine'的定義 –

+1

我發現問題 - lambda參數可以是Model或Context。這裏應該是上下文。我已經更新了你的代碼,現在它工作正常。非常感謝! –

+0

@MichalDymel很高興幫助:) – hazevich

相關問題