2016-06-08 56 views
0

我剛剛熟練掌握AutoMapper並喜歡它的工作原理。不過,我相信它可以映射我目前手動連線的一些複雜場景。有沒有人有任何建議/提示,從下面的簡化示例中刪除我的手動過程,並加快我的學習曲線?AutoMapper - 涉及函數調用的複雜映射

我有一個像源對象這樣:

public class Source 
{ 
    public Dictionary<string, object> Attributes; 
    public ComplexObject ObjectWeWantAsJson; 
} 

和目標對象,像這樣:

public class Destination 
{ 
    public string Property1; // Matches with Source.Attributes key 
    public string Property2; // Matches with Source.Attributes key 
    // etc. 
    public string Json; 
} 

我對AutoMapper配置是最小的:

var config = new MapperConfiguration(cfg => {}); 
var mapper = config.CreateMapper(); 

而且我的轉換代碼是這樣的:

var destinationList = new List<Destination>(); 
foreach (var source in sourceList) 
{ 
    var dest = mapper.Map<Dictionary<string, object>, Destination(source.Attributes); 
    // I'm pretty sure I should be able to combine this with the mapping 
    // done in line above 
    dest.Json = JsonConvert.SerializeObject(source.ObjectWeWantAsJson); 

    // I also get the impression I should be able to map a whole collection 
    // rather than iterating through each item myself 
    destinationList.Add(dest); 
} 

任何指標或建議,非常感謝。提前致謝!

回答

0

您可能有興趣使用TypeConverter編寫轉換代碼。

internal class CustomConverter : TypeConverter<List<Source>, List<Destination>> 
{ 
    protected override List<Destination> ConvertCore(List<Source> source) 
    { 
     if (source == null) return null; 
     if (!source.Any()) return null; 
     var output = new List<Destination>(); 
     output.AddRange(source.Select(a => new Destination 
     { 
      Property1 = (string)a.Attributes["Property1"], 
      Property2 = (string)a.Attributes["Property2"], 
      Json = JsonConvert.SerializeObject(a.ObjectWeWantAsJson) 
     })); 

     return output; 
    } 
} 

var source = new List<Source> 
     { 
      new Source{ 
       Attributes = new Dictionary<string,object>{ 
        {"Property1","Property1-Value"}, 
        {"Property2","Property2-Value"} 
       }, 
       ObjectWeWantAsJson = new ComplexObject{Name = "Test", Age = 27} 
      } 
     }; 

Mapper.CreateMap<List<Source>, List<Destination>>(). 
      ConvertUsing(new CustomConverter()); 

var dest = Mapper.Map<List<Destination>>(source); 
+0

感謝您的建議,但它幾乎似乎退一步具有每個屬性手動映射到一個屬性時當前解決方案不要求本(有大約20屬性映射,並有幾類這樣=很多代碼正在寫,我希望AutoMapper會否定這個需求)。我想知道是否有我可以採用的兩全其美的方法。也許是轉換器內部的映射器的屬性,但這聽起來很亂,嵌套映射器。你已經給了我一個嘗試的方法 - 試驗一下,看看我能否在轉換器中獲得自動字典映射。 – Gavin