Reputation: 13641
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[]>();
Upvotes: 1
Views: 2218
Reputation: 12661
Use ConstructUsing
.
Mapper.CreateMap<Source, Dest[]>()
.ConstructUsing(s => s.Values.Select(c => new Dest
{
Name = s.Name,
Val1 = c.Val1,
Val2 = c.Val2
}).ToList());
Upvotes: 2