2

I have an object, let's call it Sprite which has a Dictionary<string, SpriteMapImageWrapper> called SpriteImages. The key is a string, which needs to be 'stored' in the mapped object. This Dictionary needs to be mapped into a flat List<SpriteMapImageInfo>. All other properties are identical, yet the dictionary key needs to be mapped to SpriteMapImageInfo.Key. Is this possible using 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; }
}
Karl Cassar
  • 6,043
  • 10
  • 47
  • 84

2 Answers2

0

Give it a shot using .Aftermap, like in here:

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 
                        }
               );
           }
       }
     );
ederbf
  • 1,713
  • 1
  • 13
  • 18
0

Here's another way, using ConstructUsing and AfterMap:

// 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());

With the second mapping we're telling AutoMapper to construct a SpriteMapImageInfo from a KeyValuePair<string, SpriteMapImageWrapper> using the mapping definition for SpriteImageWrapper to SpriteMapImageInfo.

Next, we're using .AfterMap to assign the Key property.

Finally, we're telling AutoMapper to ignore all properties on the destination type since we've already taken care of them with ConstructUsing.

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307