AutoMapper将源子列表中的对象映射到目标子实体集合中的现有对象

我有以下情况:

public class Parent : EntityObject { EntityCollection Children { get; set; } } public class Child : EntityObject { int Id { get; set; } string Value1 { get; set; } string Value2 { get; set; } } public class ParentViewModel { List Children { get; set; } } public class ChildViewModel { int Id { get; set; } string Value1 { get; set; } string Value2 { get; set; } } Mapper.CreateMap(); Mapper.CreateMap(); 

是否可以将AutoMapper用于:

  • ParentViewModel.Children列表中的对象ParentViewModel.ChildrenParent.Children EntityCollection中具有匹配ID的对象。
  • Parent.ChildrenParentViewModel.Children中的对象创建新对象,其中在目标列表中找不到具有来自source的id的对象。
  • Parent.Children中删除对象,其中源列表中不存在目标ID。

我错了吗?

我担心automapper不是用于映射到填充对象,它会擦除​​Parent.Children你调用Map()。 你有几种方法:

  • 一个是创造自己在儿童身上执行地图的条件:

     foreach (var childviewmodel in parentviewmodel.Children) { if (!parent.Children.Select(c => c.Id).Contains(childviewmodel.Id)) { parent.Children.Add(Mapper.Map(childviewmodel)); } } 

    其他行为的其他ifs

  • 一种是创建IMappingAction并将其挂钩在BeforeMap方法中:

     class PreventOverridingOnSameIds : IMappingAction { 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() .BeforeMap(); 

    通过这种方式,您可以让automapper完成这项工作。