首页 > 解决方案 > Automapper 非常简单的嵌套映射不起作用

问题描述

我试图理解为什么这个配置不映射Company属性。它应该像这里描述的那样工作

public class CreateAccountViewModel 
{
    public string Name { get; set; }
    public string VatNumber { get; set; }
    public string Acronym { get; set; }
}

public class Account
{
    public string Name { get; set; }
    public string VatNumber { get; set; }
    public Company Company { get; set; }

}

public class Company
{
    public string Acronym { get; set; }
}

public class UnitTest
{
    [Fact]
    public void Foo() 
    {
        var config = new MapperConfiguration(cfg => 
        {
            cfg.CreateMap<CreateAccountViewModel, Account>();
            cfg.CreateMap<CreateAccountViewModel, Company>();
        });

        config.AssertConfigurationIsValid();
    }
}

测试结果:

  Message: 
    AutoMapper.AutoMapperConfigurationException : 
    Unmapped members were found. Review the types and members below.
    Add a custom mapping expression, ignore, add a custom resolver, or modify the source/destination type
    For no matching constructor, add a no-arg ctor, add optional arguments, or map all of the constructor parameters
    =====================================================================
    CreateAccountViewModel -> Account (Destination member list)
    Kairos.UnitTests.CreateAccountViewModel -> Kairos.UnitTests.Account (Destination member list)

    Unmapped properties:
    Company

标签: c#automapper

解决方案


您的案例和示例不是同一案例。在您的情况下,您需要添加自定义映射以将 Acronym 属性映射到 Company 实例。

AutoMapper从您的示例中知道如何映射CreateAccountViewModelAccountCreateAccountViewModel到,Company但不知道如何将字符串属性映射AcronymCompany.


推荐阅读