自动映射器,如果提到了ConstructUsing,则在现有对象上映射时不会触发AfterMap

时间:2019-07-10 18:33:15

标签: .net-core automapper

未触发AfterMap时遇到问题。

以下是发生此问题的条件:

  • 我想从抽象基本类型的现有对象上映射值
  • 提供
  • ConstructUsing,因为这里是选择具体类型的地方

这里是整个xunit测试(在执行dotnet new xunit -o PbAutoMapper之后):

using System;
using AutoMapper;
using Xunit;

namespace PbAutoMapper
{
    public class UnitTest1
    {
        [Fact]
        public void Test1()
        {
            var mapperConfig = new MapperConfiguration(config =>
            {
                config.CreateMap<SourceClass, BaseDestinationClass>()
                    .ConstructUsing(this.Construct)
                    .ForMember(i => i.MyNewProperty, o => o.Ignore())
                    .AfterMap(this.AfterMap);
                config.CreateMap<SourceClass, DestinationClass>();
            });
            var mapper = mapperConfig.CreateMapper();
            var src = new SourceClass { MyProperty = 1 };
            var dest = mapper.Map<BaseDestinationClass>(src);
            Assert.Equal("1", dest.MyNewProperty); // This works...
            dest = new DestinationClass();
            mapper.Map(src, dest);
            Assert.Equal("1", dest.MyNewProperty); // This failed because AfterMap wasn't triggered
        }
        private DestinationClass Construct(SourceClass s, ResolutionContext ctx)
        {
            var d = new DestinationClass();
            ctx.Mapper.Map(s, d, ctx);
            return d;
        }
        private void AfterMap(SourceClass s, BaseDestinationClass d)
        {
            d.MyNewProperty = s.MyProperty.ToString();
        }
    }
    public class SourceClass
    {
        public int MyProperty { get; set; }
    }
    public abstract class BaseDestinationClass
    {
        public string MyNewProperty { get; set; }
    }
    public class DestinationClass : BaseDestinationClass
    {
    }
}

注意:看起来似乎可以实现不同的这段代码实际上已经过简化,无法以最简单的方式揭示我的问题。

0 个答案:

没有答案