AutoMapper one to many relation

北城以北 提交于 2019-12-21 05:05:13

问题


I'm starting to use AutoMapper for my project.

For this I want to do the following 'one-to-many' mapping:

Source:

public class Team
{
    int Id { get; set; }
    string TeamName { get; set; }
    List<Person> Member { get; set; }
}

public class Person
{
    int Id { get; set; }
    string Name { get; set; }
}

Destination:

public class TeamDetailsViewModel
{
    int Id { get; set; }
    string TeamName { get; set; }
    List<int> MemberIds { get; set; }
}

How to proceed with AutoMapper? Is this possible?

Thanks a lot in advance.


回答1:


This map should work for you:

CreateMap<Team, TeamDetailsViewModel>()
    .ForMember(d=>d.MemberIds, o=>o.MapFrom(s=>s.Member.Select(m=>m.Id)));

FYI...If you are getting the Team from a db, make sure you are eager loading the Member list.



来源:https://stackoverflow.com/questions/6872610/automapper-one-to-many-relation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!