源子列表AutoMapper对象映射到现有的对象目的地子实体集 [英] AutoMapper mapping objects in source child list to existing objects in destination child entity collection
本文介绍了源子列表AutoMapper对象映射到现有的对象目的地子实体集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下情况:
public class Parent : EntityObject
{
EntityCollection<Child> Children { get; set; }
}
public class Child : EntityObject
{
int Id { get; set; }
string Value1 { get; set; }
string Value2 { get; set; }
}
public class ParentViewModel
{
List<ChildViewModel> Children { get; set; }
}
public class ChildViewModel
{
int Id { get; set; }
string Value1 { get; set; }
string Value2 { get; set; }
}
Mapper.CreateMap<ParentViewModel, Parent>();
Mapper.CreateMap<ChildViewModel, Child>();
时有可能得到AutoMapper为:
Is it possible to get AutoMapper to:
- 在
ParentViewModel.Children
列表地图对象在对象Parent.Children
EntityCollection相匹配的IDS。 - 创建为对象
Parent.Children
新对象ParentViewModel.Children
,其中来自源ID的对象没有在目的地列表中找到。 - 从
Parent.Children
其中,目标id源列表中不存在。
- Map objects in the
ParentViewModel.Children
list to objects in theParent.Children
EntityCollection with matching Ids. - Create new objects in
Parent.Children
for objects inParentViewModel.Children
where an object with the id from source is not found in the destination list. - Remove objects from
Parent.Children
where the destination id does not exist in the source list.
我要对所有这一切错了?
Am I going about this all wrong?
推荐答案
恐怕automapper并不意味着用于映射到填充对象时,它会删除该文Parent.Children调用地图() 。
。您在这里有几种方法:
I'm afraid automapper is not meant to be used for mapping to a populated object, it will erase the Parent.Children wen you invoke Map(). You have several approaches here:
-
一是创建自己的条件来执行对儿童地图:
One is to create yourself the condition to execute the map on childrens:
foreach (var childviewmodel in parentviewmodel.Children)
{
if (!parent.Children.Select(c => c.Id).Contains(childviewmodel.Id))
{
parent.Children.Add(Mapper.Map<Child>(childviewmodel));
}
}
对于其他行为的其他IFS
Other ifs for other behaviour
一是要创造一个IMappingAction,并把它挂在BeforeMap方式:
One is to create an IMappingAction and hook it in the BeforeMap method:
class PreventOverridingOnSameIds : IMappingAction<ParentViewModel, Parent>
{
public void Process (ParentViewModel source, Parent destination)
{
var matching_ids = source.Children.Select(c => c.Id).Intersect(destination.Children.Select(d => d.Id));
foreach (var id in matching_ids)
{
source.Children = source.Children.Where(c => c.Id != id).ToList();
}
}
}
..后来就
Mapper.CreateMap<ParentViewModel, Parent>()
.BeforeMap<PreventOverridingOnSameIds>();
这样,你让automapper做的工作。
this way you let automapper do the job.
这篇关于源子列表AutoMapper对象映射到现有的对象目的地子实体集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文