自动映射器:映射集合和传递参数 [英] Automapper: mapping collection and passing parameter
问题描述
我正在尝试将一个实体映射到另一个(具有一个附加字段).
I am trying to map one entity to another (which has one additional field).
Group {
int Id;
}
GroupExtended {
int Id;
string Description;
}
所以我在循环中进行映射:
So I do the mapping in loop:
foreach (var group in groups)
{
var result = mapper.Map<Group, GroupExtended>(group,
opt => opt.AfterMap((src, dest) => dest.Description = someValue));
}
是否可以映射整个IEnumerable,并且仍传递值?我试过了:
Is that possible to map entire IEnumerable, and still passing an the value ? I tried this:
var result = mapper.Map<List<GroupExtended>>(groups,
opt => opt.AfterMap((src, dest) => dest.Description = someValue));
但是在 dest.Description
上有错误:'object'不包含"Description"的定义
But it has an error on dest.Description
: 'object' does not contain definition of "Description"
推荐答案
是的,可以映射整个集合并仍然传递值.首选使用自定义值解析器,因为在您对原始帖子的评论中指出.如果仍然希望使用 AfterMap
,则可以执行以下操作,请记住,在这种情况下,您的源和目标是集合,而不是单个项目:
Yes, it is possible to map an entire collection and still pass the value. Using a custom value resolver is probably the preferred option, as pointed out in the comment on your original post. If you'd still prefer to use AfterMap
, you can do something like the following, remembering that your source and destination in this case are collections rather than individual items:
var result = mapper.Map<List<Group>, List<GroupExtended>>(groups,
opt => opt.AfterMap((src, dest) =>
{
foreach (var i in dest)
{
i.Description = "someValue";
}
}));
这篇关于自动映射器:映射集合和传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!