2015-04-21 47 views
2

我有一個對象,我們稱之爲Sprite,它有一個叫做SpriteImagesDictionary<string, SpriteMapImageWrapper>。關鍵是一個字符串,它需要被存儲在映射的對象中。這本詞典需要映射到一個單位List<SpriteMapImageInfo>。所有其他屬性都是相同的,但字典密鑰需要映射到SpriteMapImageInfo.Key。這可能使用AutoMapper?使用AutoMapper將字典映射到列表並存儲它的密鑰

public class SpriteMapImageWrapper 
{ 
    public int X { get; set; } 
    public int Y { get; set; } 
    public int Width { get; set; } 
    public int Height { get; set; } 
} 
public class SpriteMapImageInfo 
{ 
    public string Key { get; set; } 
    public int X { get; set; } 
    public int Y { get; set; } 
    public int Width { get; set; } 
    public int Height { get; set; } 
} 

回答

0

給它使用.Aftermap,一出手就像這裏:

Mapper.CreateMap<Sprite, List<SpriteMapImageInfo>>() 
     .AfterMap((u, t) => 
     { 
      foreach(var s in u.SpriteImages) 
      { 
       t.Add(new SpriteMapImageInfo 
         { 
          Key = s.Key, 
          Height = s.Value.Height, 
          Width = s.Value.Width, 
          X = s.Value.X, 
          Y = s.Value.Y 
         } 
       ); 
      } 
     } 
    ); 
0

這裏的另一種方式,利用ConstructUsingAfterMap

// Create an "inner" mapping 
Mapper.CreateMap<SpriteMapImageWrapper, SpriteMapImageInfo>() 
    .ForMember(dest => dest.Key, opt => opt.Ignore()); 

// Create an "outer" mapping that uses the "inner" mapping 
Mapper.CreateMap<KeyValuePair<string, SpriteMapImageWrapper>, SpriteMapImageInfo>() 
    .ConstructUsing(kvp => Mapper.Map<SpriteMapImageInfo>(kvp.Value)) 
    .AfterMap((src, dest) => dest.Key = src.Key) 
    .ForAllMembers(opt => opt.Ignore()); 

隨着我們告訴AutoMapper第二映射使用SpriteImageWrapper到01的映射定義從KeyValuePair<string, SpriteMapImageWrapper>構造。

接下來,我們使用.AfterMap來指定Key屬性。

最後,我們告訴AutoMapper忽略目標類型的所有屬性,因爲我們已經用ConstructUsing來照顧它們。

相關問題