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

时间:2011-01-07 00:36:07

标签: c# entity-framework 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设置为:

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

我是不是错了?

1 个答案:

答案 0 :(得分:2)

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