开发者

AutoMapper one to many relation

开发者 https://www.devze.com 2023-03-23 23:52 出处:网络
I\'m starting to use AutoMapper for my project. For this I want to do the following \'one-to-many\' mapping:

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.


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.

0

精彩评论

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