使用Automapper映射List <t>的属性

时间:2015-07-13 20:26:21

标签: c# string linq automapper

使用Automapper,我想使用string.Join()来映射属于Employee类型的List的属性,以生成以逗号分隔的员工权限名称字符串。以下是我使用的课程:

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]

我该怎么做才能获得以逗号分隔的员工权利字符串?

1 个答案:

答案 0 :(得分:2)

尝试使用ResolveUsing代替并在选择前加string.Join

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