繁体   English   中英

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

[英]AutoMapper mapping objects in source child list to existing objects in destination child entity collection

我有以下情况:

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用于:

  • 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<Child>(childviewmodel)); } } 

    其他行为的其他ifs

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

     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完成这项工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM