2011-06-02 66 views
8

我想使用automapper为父对象创建单个映射,并在它的子项中重新使用它。自动映射器继承 - 重用地图

对于儿童属性,我只想映射额外的字段。

这可能吗?代码我看起来像这样

CreateCalculationMap(message); ---- This does the BASE parent mappping. 
    Mapper.CreateMap<QuoteMessage, CalculationGipMessage>()      -- This is the child. 
     .Include<QuoteMessage, CalculationBase>()        -- Include the parent? 
     .ForMember(a => a.OngoingCommission, b => b.MapFrom(c => c.OngoingASF)) - Child 
     .ForMember(a => a.SpecialRate, b => b.MapFrom(c => c.BlahBlah)));  - Child 

为什么它会告诉我父母的属性没有映射?然而,我想我把它们包含在CreateCalculationMap(message)中;其中包含

Mapper.CreateMap<QuoteMessage, CalculationBase>()() 

回答

6

来源FYI我想通了这一点

public static IMappingExpression<A, T> ApplyBaseQuoteMapping<A, T>(this IMappingExpression<A, T> iMappingExpression) 
     where A : QuoteMessage 
     where T : CalculationGipMessage 
    { 
     iMappingExpression 
      .ForMember(a => a.LoginUserName, b=> b.MapFrom(c => c.LoginUserName)) 
      .ForMember(a => a.AssetTestExempt, b => b.Ignore()) 
      ; 

     return iMappingExpression; 
    } 


Mapper.CreateMap<QuoteMessage, CalculationGipMessageChild>() 
      .ApplyBaseQuoteMappingToOldCol() 
      // do other mappings here 
0

你不能这样做我不认为 - 你需要有映射在一起。这可能实际上是一个错误,因为维基宣称它可以完成 - 但是给出的示例仅仅依赖于属性的名称来执行映射,而不是包含位。至少我是这么理解的。

如果你看http://automapper.codeplex.com/wikipage?title=Lists%20and%20Arrays并更改源和目​​的地属性的名称(我让它们的值3和值4真正混合起来)然后明确地添加你的映射。

Mapper.CreateMap<ChildSource, ChildDestination>() 
      .ForMember(x => x.Value4, o => o.MapFrom(y => y.Value2)); 
     Mapper.CreateMap<ParentSource, ParentDestination>() 
      .Include<ChildSource, ChildDestination>() 
      .ForMember(x => x.Value3, o => o.MapFrom(y => y.Value1)); 

然后它似乎失败了。

 ChildSource s = new ChildSource() 
     { 
      Value2 = 1, 
      Value1 = 3 
     }; 

     var c = s.MapTo<ChildDestination>(); 
     var c2 = s.MapTo<ParentDestination>(); 

     Assert.AreEqual(c.Value3, s.Value1); 
     Assert.AreEqual(c.Value4, s.Value2); 
     Assert.AreEqual(c2.Value3, s.Value1); 
     Assert.AreEqual(c.Value4, s.Value2); 

其他注意事项

另外,包括需要为孩子不是父。原型其实这个规定

public IMappingExpression<TSource, TDestination> Include<TOtherSource, TOtherDestination>() 
     where TOtherSource : TSource 
     where TOtherDestination : TDestination 

从我读过你应该先创建子映射,尽管这可能是一个老问题。

Mapper.CreateMap<ChildSource, ChildDest>(); 

,那么父

Mapper.CreateMap<ParentSource, Parent Dest>() 
     .Include<ChildSource, ChildDest>(); 

http://automapper.codeplex.com/wikipage?title=Lists%20and%20Arrays