AutoMapper maps objects in the source child list to existing objects in the destination child collection

I have the following situation:

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>();

Is it possible to get AutoMapper:

  • Display objects in the list ParentViewModel.Childrenfor objects in Parent.ChildrenEntityCollection with the corresponding identifiers.
  • Create new objects in Parent.Childrenfor objects in ParentViewModel.Children, where the object with the identifier from the source is not found in the mailing list.
  • Remove objects from Parent.Childrenwhere the destination identifier does not exist in the source list.

Am I really doing all this wrong?

+3
source share
1 answer

, automapper , . 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>();
    

    .

+2

Source: https://habr.com/ru/post/1783975/


All Articles