1

How can I reconcile a list using auto mapper?

For example given a class

public class SomeEntity
{
    public Guid Id {get; set;}
    public string Name {get; set;}
}

And an overaching class

public class SomeAggregate
{
    public IEnumerable<SomeEntity> EntityEnumeration {get;set;}
}

For the sake of this question (my actual requirement is a bit different). I need to map an instance of SomeAggregate to another instance of it. I want to use AutoMapper, but I need to customize how the EntityEnumeration is populated.

This is what I'm trying to achieve:

Mapper.CreateMap<SomeAggregate,SomeAggregate>()
    .ForMember(d => d.SomeAggregate, *** MISSING LOGIC ***);

Mapper.Map(newInstance, existing);

* MISSING LOGIC * needs to be replaced with a code that checks for:

  1. If it's null, then copy all of RHS
  2. If it's not null, check if the LHS has a member with the same Id, if not add the member from the RHS.
  3. If LHS has the same Id, just update the Name property of the matching entity.
  4. If LHS has an Id that doesn't exist in the RHS, remove the Id from the LHS.

I don't even know where to start, because I can't get an instance of the LHS and the RHS in the same lambda delegate to do this kind of comparison. At least none of the build in options seems to let me do this kind of mapping. I'd think this should be a fairly common use case.

Please help.

Alwyn
  • 8,079
  • 12
  • 59
  • 107
  • 1
    Sounds similar to these questions http://stackoverflow.com/questions/16063619/automapper-hydrate-int-based-on-conditions/ http://stackoverflow.com/questions/12262940/usedestinationvalue-only-when-destination-property-is-not-null http://stackoverflow.com/questions/4503200/can-automapper-ignore-destination-if-it-is-not-null-only-change-null-fields You may be able to do what you need in `BeforeMap` or `AfterMap`. – Mightymuke Apr 25 '13 at 02:27
  • @Mightymuke I think I can work with that. Thank you! – Alwyn Apr 25 '13 at 03:31

0 Answers0