在automapper中展平1对多的类

时间:2011-03-17 15:29:04

标签: c# automapper

我有一个源和目标对象,如下所示:

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

我基本上想要展平一对多关系,复制Name属性,结果将是:

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

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

有没有办法用automapper做到这一点?

2 个答案:

答案 0 :(得分:1)

我不认为AutoMapper可以自动从单个团队转到MyDTOObjects的数组/集合。但是,用LINQ做你想要的东西应该很容易:

var flattened = from p in team.Persons
                select new MyDTOClass { TeamName = team.Name, PersonName = p.FullName}

答案 1 :(得分:0)

我刚刚开始使用Automapper,但这是我能够提供的解决方案:

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