AutoMapper change type
Considering 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 inherited some legacy code, List should be in base class A and B).
With some new classes
public class AFooEquipment : FooEquipment
{
}
public class BFooEquipment : FooEquipment
{
}
Can AutoMapper be used to convert these FooEquipments
to AFooEquipment
and BFooEquipment
by checking their parent? That is, In the mapper, I would see that object1 is in the typeof (A) class, so I convert its hardware -> List<AFooEquipment>
. He will see that object2 is in the typeof (B) class, so I convert his hardware -> List<BFooEquipment>
.
Is it possible?
source to share
I am using AutoMapper 3, so it may not work for you, but one option would be to use methods ResolutionContext
and ConstructUsing
, 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)
, he should give you what you want. Or what I suspect you want :)
source to share