1

I have a source and destination object like so:

Source:
public class Team{
  public string TeamName{get; set;}
  public string List<Person> {get; set;}
}

public class Person{
  public string FullName {get; set;}
}

Destination:
public class MyDTOClass{
  public string TeamName;
  public string PersonName;
}

I basically want to flatten a one-to-many relationship, duplicating the Name property, so the result would be:

   MyDtoClass.TeamName= "X";
   MyDtoClass.PersonName= "Y";

   MyDtoClass.TeamName= "X";
   MyDtoClass.PersonName= "Z"; 

Is there a way to do this with automapper?

Dan
  • 1,222
  • 2
  • 17
  • 33

2 Answers2

1

I don't think AutoMapper can automatically go from a single Team to an array/collection of MyDTOObjects. However, it should be pretty easy to do what you want with LINQ:

var flattened = from p in team.Persons
                select new MyDTOClass { TeamName = team.Name, PersonName = p.FullName}
PatrickSteele
  • 14,489
  • 2
  • 51
  • 54
  • I was looking at this example http://stackoverflow.com/questions/3471333/mapping-from-list-down-to-object-with-automapper, which seems to suggest it can be done, but I just don't know how to do it. Or am I missing something? – Dan Mar 17 '11 at 18:42
  • But even it that example, it's a 1:1 mapping. You want to go 1:many, which I don't think Automapper supports. I think your best bet would be to have a wrapper class that contains a List and use the LINQ statement above to do the mapping for the list member. Let me know if you want an example of that. – PatrickSteele Mar 17 '11 at 20:33
0

I just started using Automapper, but here is solution I was able to come with:

Func<Team[], IEnumerable<MyDTOClass>> getPersonsFromTeams = (teams) => new IEnumerable<MyDTOClass>
{
    teams.SelectMany(s => s.Persons, (t, person) => new MyDTOClass(team.TeamName, person))
};

mapper.CreateMap<Company, CompanyDTOs>()
    .ForMember(d => d.Persons, o => o.ResolveUsing(s => s.getPersonsFromTeams(s.Teams)));