自动传递器继承 - 重用地图

时间:2011-06-02 09:11:14

标签: c# automapper

我正在尝试使用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(消息)中;其中包含

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

2 个答案:

答案 0 :(得分:6)

仅供参考我想出了这个

 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

答案 1 :(得分:0)

你不能这样做我不认为 - 你需要将映射放在一起。这实际上可能是一个错误,因为维基声称它可以完成 - 但是给出的示例只是依靠属性的名称来进行映射,而不是包含位。至少这是我理解它的方式。

如果您查看http://automapper.codeplex.com/wikipage?title=Lists%20and%20Arrays并更改Source和Dest中的属性名称(我将它们设置为Value 3和Value4以实际混合),那么明确地添加您的映射。

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

其他笔记

此外,Include需要是孩子而不是父母。原型实际上说明了这个

    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