3

Given the following:

var object1 = new A() { Equipment = new List<FooEquipment>() { new FooEquipment() } };
var object2 = new B() { Equipment = new List<FooEquipment>() { new FooEquipment() } );

var list = new List<Foo>() { object1, object2 };

(I've inherited some legacy code, the List should be in the base class of A and B).

With some new classes,

public class AFooEquipment : FooEquipment
{
}

public class BFooEquipment : FooEquipment
{
}

Can I use AutoMapper to convert these FooEquipments into AFooEquipment and BFooEquipment by inspecting their parent item somehow? I.e. In the mapper I would see object1 is in a typeof(A) class, so I convert its equipment -> List<AFooEquipment>. It would see object2 is in a typeof(B) class, so I convert its equipment -> List<BFooEquipment>.

Is that possible?

Sebastian Patten
  • 7,157
  • 4
  • 45
  • 51

1 Answers1

1

I am using AutoMapper 3 so this may not work for you, but one option would be to use the ResolutionContext and ConstructUsing method, something like this:

CreateMap<Foo, Foo>()
  .Include<A, Foo>()
  .Include<B, Foo>();
CreateMap<A, A>();
CreateMap<B, B>();
CreateMap<FooEquipment, FooEquipment>()
  .ConstructUsing((ResolutionContext ctx) =>
  {
    if (ctx.Parent != null) // Parent will point to the Equipment property
    {
      var fooParent = ctx.Parent.Parent; // Will point to Foo, either A or B.
      if (fooParent != null)
      {
        if (fooParent.SourceType == typeof(A)) return new AFooEquipment();
        if (fooParent.SourceType == typeof(B)) return new BFooEquipment();
      }
    }
    return new FooEquipment();
  });

If you then call Mapper.Map<IEnumerable<Foo>>(list) it should give you what you want. Or what I suspect you want :)

Patko
  • 4,365
  • 1
  • 32
  • 27