我一直在筛选 AutoMapper 文档,试图找到针对此问题的推荐解决方案,但未能找到。
假设我有一个像下面这样的类
public class Foo
{
public string Note { get; set; }
}
此类从客户端填充并映射到以下域对象类
public class Bar
{
public IList<Note> Notes { get; set; }
}
注释在哪里
public class Note
{
public string Text { get; set; }
// other properties excluded for brevity
}
我想将 Note
字符串属性映射到 Foo
上,首先映射到 的新实例上的
,然后将该 Text
属性NoteNote
添加到 Bar
上的 Notes
集合中。我正在使用 ValueResolver
来执行此操作的第一部分(将字符串映射到 Note
的新实例)但不确定如何进行第二部分部分(将该项目映射到集合中的项目)。
这样做最干净的方法是什么?
最佳答案
我认为这样的事情应该可行(未经测试——只是大声输入):
Mapper.CreateMap<Foo, Bar>().ForMember(d => d.Notes,
opt => opt.MapFrom(s => new List<Note> { new Note { Text = s.Note } });
编辑
您还可以使用 AutoMappers AfterMap
功能。这个 lambda 将在 Automapper 完成它的常规映射后执行:
.AfterMap((s,d) => d.Notes.Add(new Note { Text = s.Note }));
关于c# - 将属性映射到集合项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4733410/