当被要求时,Automapper不会忽略第二级嵌套属性

时间:2011-12-07 13:20:21

标签: c# .net automapper

在Automapper'忽略'选项中遇到一些问题。这是一个测试,概述了我遇到的问题:

    using AutoMapper;
    using NUnit.Framework;

    [TestFixture]
    public class Sample
    {
        public class OuterSource
        {
            public InnerSource Inner { get; set; }
        }

        public class InnerSource
        {
            public InnerInnerSource InnerInner { get; set; }
        }

        public class InnerInnerSource
        {
            public int Value { get; set; }
        }

        public class OuterDest
        {
            public InnerDest Inner { get; set; }
        }

        public class InnerDest
        {
            public InnerInnerDest InnerInner { get; set; }
        }

        public class InnerInnerDest
        {
            public int Value { get; set; }
        }

        [Test]
        public void MergeMap_WhenIgnoringLevel2InnerProperty_PropertyRemainsUnchanged()
        {
            Mapper.CreateMap<OuterSource, OuterDest>();
                //.ForMember(d => d.Inner, opts => opts.Ignore());  // test passes when added back in
            Mapper.CreateMap<InnerSource, InnerDest>()
                .ForMember(d => d.InnerInner, opts => opts.Ignore());

            var source = new OuterSource { Inner = new InnerSource { InnerInner = new InnerInnerSource { Value = 25 } } };

            var destination = new OuterDest { Inner = new InnerDest { InnerInner = new InnerInnerDest { Value = 99 } } };

            Mapper.Map(source, destination);

            Assert.That(99 == destination.Inner.InnerInner.Value);  // FAIL - destination.Inner.InnerInner is null
        }
    }

似乎'ignore'选项不能完全正常工作。如果我在第一个'忽略'中回复,那么一切都按预期工作。问题是我需要映射的Inner类上有许多其他属性。唯一要忽略的是InnerInner类。

有什么想法吗?我认为同样的问题已被概述here,但接受的答案对我不起作用。

2 个答案:

答案 0 :(得分:2)

使用AutoMapper的建议方法是映射类型,就像引用的帖子中提到的那样。因此,您永远不会创建目标对象,只需指定要映射到的类型即可。

var dest = Mapper.Map<OuterSource, OuterDest>(source);

您是否有可能以这种方式使用它,然后在稍后的时间点设置dest.InnerInner的值?

答案 1 :(得分:0)

Mapper.CreateMap<InnerSource, InnerDest>()
    .ForMember(d => d.InnerInner, opts => opts.UseDestinationValue());

Mapper.CreateMap<OuterSource, OuterDest>()
    .ForMember(d => d.Inner, opts => opts.UseDestinationValue())
    .AfterMap((source, destination) => Mapper.Map(source.Inner, destination.Inner));