Q:AutoMapper 无法在目标中使用 TypeCode

Q:AutoMapper unable to use TypeCode in Destination

我遇到了一个非常奇怪的问题,当我在 Destination,Map方法会抛出异常。有谁知道如何解决它?谢谢

public class Source
{
    public int Id { get; set; }
}

public class Destination
{
    public int Id { get; set; }
    public decimal IdTypeCode { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var configuration = new MapperConfiguration(c => c.CreateMap<Source, Destination>());
        var mapper = configuration.CreateMapper();
        //will throw an exception
        var dest = mapper.Map<Destination>(new Source
        {
            Id = 1
        });
    }
}

我相信这是 AutoMapper 试图将源 Id 属性“flatten”到目标对象中的副作用。

由于您的目标具有 属性 IdTypeCode,AutoMapper 将尝试从源中找到匹配值。在这种情况下,它似乎正在使用 Source.Id 属性 上的 Type.GetTypeCode() 方法,因此试图将 System.TypeCode 映射到 decimal .这可以在抛出的异常中看到:

Destination Member: IdTypeCode

 ---> AutoMapper.AutoMapperMappingException: Missing type map configuration or unsupported mapping.

Mapping types: 
TypeCode -> Decimal 
System.TypeCode -> System.Decimal

这可以通过将 Destination.IdTypeCode 的类型更改为 System.TypeCode:

来验证
public class Source
{
    public int Id { get; set; }
}

public class Destination
{
    public int Id { get; set; }
    public TypeCode IdTypeCode { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var configuration = new MapperConfiguration(c => c.CreateMap<Source, Destination>());
        var mapper = configuration.CreateMapper();
        //will throw an exception
        var dest = mapper.Map<Destination>(new Source
        {
            Id = 1
        });

        Console.WriteLine(dest.IdTypeCode);
    }
}

这会导致映射成功并且 Destination.IdTypeCode 被映射为值 Int32


话虽如此,除了更改 属性 的名称外,一个简单的解决方案就是忽略目标上的 属性:

var configuration = new MapperConfiguration(c =>
    {
        c.CreateMap<Source, Destination>()
            .ForMember(d => d.IdTypeCode, opt => opt.Ignore());
    });

根据 Lucian 的回答,我修改了我的代码如下,效果很好

    public class Source
    {
        public string Card { get; set; }
    }

    public class Destination
    {
        public string Card { get; set; }
        public decimal CardTypeCode { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var configuration = new MapperConfiguration(configure =>
            {
                //set this func
                configure.ShouldMapMethod = _ => false;
                configure.CreateMap<Source, Destination>();
            });
            var mapper = configuration.CreateMapper();
            var dest = mapper.Map<Destination>(new Source
            {
                Card = "1"
            });
        }
    }