2014-10-21 3 views
3

는 :AutoMapper 변경 유형

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 }; 

(좀 레거시 코드를 상속 한 목록은 A와 B의 기본 클래스에 있어야합니다). 새로운 클래스와

,

public class AFooEquipment : FooEquipment 
{ 
} 

public class BFooEquipment : FooEquipment 
{ 
} 

나는 AutoMapper 어떻게 든 상위 항목을 검사하여 AFooEquipmentBFooEquipment에 이러한 FooEquipments을 변환 할 수 있습니까? 나는. mapper에서 object1이 typeof (A) 클래스에 있다는 것을 알았 기 때문에 해당 장비를 변환합니다. ->List<AFooEquipment>. object2가 typeof (B) 클래스에 있다는 것을 알았 기 때문에 장비를 변환합니다 ->List<BFooEquipment>.

그럴 수 있습니까? 그것은 당신을 제공한다 당신이 다음 Mapper.Map<IEnumerable<Foo>>(list)를 호출하는 경우

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

: 내가 지금이 당신을 위해 작동하지 않을 수 있습니다 AutoMapper 3을 사용하고

+0

네, 실제로 아주 쉽게. – Darek

+0

시도해 보셨습니까? https://github.com/AutoMapper/AutoMapper/wiki/Mapping-inheritance –

+0

나는 내 코드의 다른 부분에서이 접근법을 성공적으로 사용했다. 나는이 인스턴스를 시도했지만 작동하지 않는 것 같았다. 그것이 틀림없이 올바른 접근법이라면, 아마 내가 잘못 매핑 한 것일 수도 있습니다. –

답변

1

하지만, 하나의 옵션은이 같은 ResolutionContextConstructUsing 방법, 뭔가를 사용하는 것 당신이 원하는. 또는 내가 뭘 원하는지 의심 :)

관련 문제