C# 带有嵌套子列表的 Automapper
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9394833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 07:11:07 来源:igfitidea点击:
Automapper with nested child list
提问by tobias
I have two classes below:
我有以下两个类:
public class Module
{
public int Id { get; set; }
public string Name { get; set; }
public string ImageName { get; set; }
public virtual ICollection<Page> Pages { get; set; }
}
public class ModuleUI
{
public int Id { get; set; }
public string Text { get; set; }
public string ImagePath { get; set; }
public List<PageUI> PageUIs { get; set; }
}
The mapping must be like this:
映射必须是这样的:
Id -> Id
Name -> Text
ImageName -> ImagePath
Pages -> PageUIs
How can I do this using Automapper?
如何使用 Automapper 执行此操作?
采纳答案by nemesv
You can use ForMemberand MapFrom(documentation).
Your Mapper configuration could be:
您可以使用ForMember和MapFrom(文档)。
您的 Mapper 配置可能是:
Mapper.CreateMap<Module, ModuleUI>()
.ForMember(s => s.Text, c => c.MapFrom(m => m.Name))
.ForMember(s => s.ImagePath, c => c.MapFrom(m => m.ImageName))
.ForMember(s => s.PageUIs, c => c.MapFrom(m => m.Pages));
Mapper.CreateMap<Page, PageUI>();
Usage:
用法:
var dest = Mapper.Map<ModuleUI>(
new Module
{
Name = "sds",
Id = 2,
ImageName = "sds",
Pages = new List<Page>
{
new Page(),
new Page()
}
});
Result:
结果:



