简体   繁体   English

映射列表的属性 <T> 使用自动映射器

[英]Mapping A Property Of List<T> Using Automapper

Using Automapper, I want to map a property that is a List of type Employee using string.Join() to product a comma-delimited string of the names of an employee's rights. 使用自动映射器,我想使用string.Join()映射一个类型为Employee的List的属性,以产生一个以逗号分隔的员工权利名称的字符串。 Here are the classes I'm using: 这是我正在使用的类:

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; }
}

And here is the code I have: 这是我的代码:

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);

However, this it's producing the folowing: 但是,这导致了以下问题:

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

What can I do do get a comma-delimited string of the Employee's rights? 我该怎么办才能获得以逗号分隔的员工权利字符串?

Try using ResolveUsing instead and putting string.Join before the selection: 尝试改用ResolveUsing并将string.Join加入选择之前:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM