1

作为 AutoMapper 的新粉丝,我将如何使用它来执行以下操作:

给定以下类,我想从 Group 创建 FlattenedGroup,其中项目字符串列表映射到 Item 的 title 属性。

public class Group
{
    public string Category { get; set; }
    public IEnumerable<Item> Items { get; set; }
}

public class Item
{
    public int ID { get; set; }
    public string Title { get; set; }
}


public class FlattenedGroup
{
    public string Category { get; set; }
    public IEnumerable<string> Items { get; set; }
}

谢谢

约瑟夫

4

2 回答 2

7

您可以做的另一件事是从 Item -> string 创建一个转换器:

Mapper.CreateMap<Item, string>().ConvertUsing(item => item.Title);

现在你不需要在你的 Group -> FlattenedGroup 地图中做任何特别的事情:

Mapper.CreateMap<Group, FlattenedGroup>();

这就是你所需要的。

于 2010-01-11T13:50:21.543 回答
1

试一试,您可能可以使用 Linq 和 lambda 表达式将 FlattenedGroup 中的字符串列表与 Group 中的标题进行映射。

Mapper.CreateMap<Group, FlattenedGroup>()
                .ForMember(f => f.Category, opt => opt.MapFrom(g => g.Category))
                .ForMember(f => f.Items, opt => opt.MapFrom(g => g.Items.Select(d => d.Title).ToList()));

确保将 System.Linq 添加到 using 语句

于 2010-01-11T03:16:00.847 回答