Automapper ProjectTo从子级访问父级

时间:2018-02-15 19:51:34

标签: c# automapper

从ProjectTo doesn't support BeforeMap开始,如何将parent对象传递给children集合?这是代码:

void Main()
{
    Mapper.Initialize(c =>
    {
        c.AddProfile<Prof>();
    });

    myDbContext.Profiles
        .ProjectTo<ProfileDto>()
        .Dump(); // Linqpad Extension

}

public class Prof : Profile
{
    public Prof()
    {
        CreateMap<ProfileEntity, ProfileDto>();
        CreateMap<UserEntity, UserDto>();
    }
}

public class ProfileDto
{
    public string Name { get; set; }
    public IEnumerable<UserDto> Users { get; set; }
}

public class UserDto
{
    public string Name { get; set; }
    public string ProfileName { get; set; }
}

我只想填写“ProfileName”属性。

1 个答案:

答案 0 :(得分:1)

像这样使用AutoMapperConfiguration:

cfg.CreateMap<Prof, ProfileDto>()
                .ForMember(d => d.Users, opt => opt.MapFrom(src => src.Users.Select(x=>new UserDto { Name=x.Name,ProfileName=src.Name})));