为什么不';t此AutoMapper映射工作

本文关键字:AutoMapper 映射 工作 为什么不 | 更新日期: 2023-09-27 18:26:43

我不明白为什么这不起作用?这两个字段在destinationDTO上都映射为NULL。使用AutoMapper v4.1.1

[TestFixture]
public class AutoMapperTests
{
    [SetUp]
    public void Init()
    {
        AutoMapperTestConfiguration.Configure();
    }
    [Test]
    public void Mapping_With_Underscores()
    {
        SourceDTO source = new SourceDTO
        {
            first_name = "John",
            last_name = "Doe"
        };
        var result = Mapper.Map<DestinationDTO>(source);
        Assert.That(result.FirstName == "John");
    }
}

public class SourceDTO
{
    public string first_name { get; set; }
    public string last_name { get; set; }
}
public class DestinationDTO
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
public class AutoMapperTestConfiguration
{
    public static void Configure()
    {
        Mapper.Initialize(x =>
        {
            x.AddProfile<FromUnderscoreMapping>();
        });
    }
}
public class FromUnderscoreMapping : Profile
{
    protected override void Configure()
    {
        this.SourceMemberNamingConvention = new LowerUnderscoreNamingConvention();
        this.DestinationMemberNamingConvention = new PascalCaseNamingConvention();
        Mapper.CreateMap<SourceDTO, DestinationDTO>();
    }
}

为什么不';t此AutoMapper映射工作

哎哟,这让我有一段时间了。问题出在这条线上

Mapper.CreateMap<SourceDTO, DestinationDTO>();

我调用的是全局AutoMapper实例,而不是继承的Profile,它覆盖了命名约定。简单地删除Mapper就解决了这个问题。

CreateMap<SourceDTO, DestinationDTO>();

我在这件事上浪费了很多时间。