Dan
Dan

Reputation: 1262

Flattening 1-to-many classes in automapper

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?

Upvotes: 1

Views: 2514

Answers (2)

user1978424
user1978424

Reputation: 27

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

Upvotes: 0

PatrickSteele
PatrickSteele

Reputation: 14677

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}

Upvotes: 1

Related Questions