映射List

本文关键字:一个 属性 Automapper List gt 映射 | 更新日期: 2023-09-27 18:02:32

使用Automapper,我想映射一个Employee类型的List属性,使用string. join()生成一个以逗号分隔的员工权利名称字符串。下面是我使用的类:

public class MappedEmployee
{
    public string Name { get; set; }
    public string RightNames { get; set; }
}
public class Employee
{
    public string Name { get; set; }
    public List<Right> Rights { get; set; }
}
public class Right
{
    public string Name { get; set; }
}

下面是我的代码:

Mapper.CreateMap<Employee, MappedEmployee>()
    .ForMember(d => d.RightNames, o => o.MapFrom(s => s.Rights.SelectMany(r => string.Join(", ", r.Name))));
var employee = new Employee
{
    Name = "Joe Schmoe",
    Rights = new List<Right>
    {
        new Right { Name = "Admin" },
        new Right { Name = "User" },
    }
};
var mappedEmployee = Mapper.Map<Employee, MappedEmployee>(employee);

然而,它产生了以下内容:

System.Linq.Enumerable+<SelectManyIterator>d__14`2[Employee.Right,System.Char]

如何获取以逗号分隔的Employee的权利字符串?

映射List<T>的一个属性使用Automapper

尝试使用ResolveUsing并将string.Join放在选择项之前:

Mapper.CreateMap<Employee, MappedEmployee>()
    .ForMember(d => d.RightNames, o => o.ResolveUsing(s => string.Join(", ",s.Rights.Select(r =>  r.Name))));