1

I'm using .NET 4.5 and Automapper 3.0

I have a source object with an array of Child objects as a property:

public class Source
{
    public string Name { get; set; }
    public Child[] Values { get; set; }
}

public class Child
{
    public string Val1 { get; set; }
    public string Val2 { get; set; }
}

My destination object is flat

public class Dest
{
    public string Name { get; set; }
    public string Val1 { get; set; }
    public string Val2 { get; set; }
}

What I need to do is map a single instance of Source to a collection of Dest (IList, Dest[], doesn't matter what kind of collection).

That is, for a single instance of Source with

Name = "MySource"
Dest = [Val1 = "A", Val2 = "B"]
       [Val1 = "C", Val2 = "D"]

I need to return a 2 item collection of Dest

Dest[0]: {Name="MySource", Val1="A", Val2="B"}
Dest[1]: {Name="MySource", Val1="C", Val2="D"}

Can this be done with automapper?

I've tried the following, none of which work (obviously):

Mapper.CreateMap<Source,Dest>();
var items = Mapper.Map<Source,Dest>();

Mapper.CreateMap<Source,Dest[]>();
var items = Mapper.Map<Source,Dest[]>();

Mapper.Createmap<Source,Dest>();
var items = Mapper.map<Source,Dest[]>();
squillman
  • 13,363
  • 3
  • 41
  • 60

1 Answers1

2

Use ConstructUsing.

Mapper.CreateMap<Source, Dest[]>()
    .ConstructUsing(s => s.Values.Select(c => new Dest 
        { 
            Name = s.Name,
            Val1 = c.Val1,
            Val2 = c.Val2
        }).ToList());
Rob Lyndon
  • 12,089
  • 5
  • 49
  • 74
  • Great, thanks! Not much more benefit than just using LINQ then in this case? – squillman Oct 16 '13 at 22:10
  • 1
    True -- if your whole mapping is defined by `ConstructUsing`, you lose a lot of the benefits of inferring fields by name. However, if you have a number of other fields in addition to `Name`, you might benefit from a call to `Mapper.Map()` within the `ConstructUsing` statement. That would be overcomplicated in this case, though. – Rob Lyndon Oct 16 '13 at 22:19