开发者

Flattening 1-to-many classes in automapper

I have a source and destination object like so:

Source:
public 开发者_如何学Goclass 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?


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}


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜