为什么这个 AutoMapper 配置不能正确映射?

Why won't this AutoMapper configuration map properly?

鉴于下面的代码,为什么我在映射阶段不断收到异常? 2个DTO真的那么不同吗?这是抛出异常的符号服务器 pdb 中的代码行。

throw new AutoMapperMappingException(context, "Missing type map configuration or unsupported mapping.");

真正让我难受的是@jbogard 在 AutoMapper 方面做了异常处理和检测的杀手级工作,源对象和目标对象都有大量上下文数据,以及映射器的状态抛出异常..我还是想不通。

void Main()
{
    var config = new MapperConfiguration(cfg =>
    {
        cfg.ShouldMapProperty = p => p.GetMethod.IsPublic || p.GetMethod.IsVirtual;
        cfg.CreateMap<Customer, Customer2>()
        .ReverseMap();
    });

    config.AssertConfigurationIsValid();

    Customer request = new Customer
    {
        FirstName = "Hello", LastName = "World"
    };
    request.FullName = request.FirstName + " " + request.LastName;

    Customer2 entity = Mapper.Map<Customer, Customer2>(request);


    Console.WriteLine("finished");
}



public class Customer
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string FullName { get; set; }
}

[Serializable()]
public partial class Customer2
{
    private string _firstName;
    private string _lastName;
    private string _fullName;

    public virtual string FirstName
    {
        get
        {
            return this._firstName;
        }
        set
        {
            this._firstName = value;
        }
    }
    public virtual string LastName
    {
        get
        {
            return this._lastName;
        }
        set
        {
            this._lastName = value;
        }
    }
    public virtual string FullName
    {
        get
        {
            return this._fullName;
        }
        set
        {
            this._fullName = value;
        }
    }
}

谢谢, 斯蒂芬

拉取源代码并将 AutoMapper.Net4 项目添加到控制台后,我能够诊断出问题。

API 引入时 Jimmy 删除了静态版本,然后在我措手不及的情况下将其重新添加回来,无论如何,语法现在与新的 API 有点不同。下面是添加源时的异常,请注意这与最初通过 Nuget 抛出的区别?

throw new InvalidOperationException("Mapper not initialized. Call Initialize with appropriate configuration."); 

这让我直接回到 GitHub 上的 Getting Started Docs,在那里我很快发现我没有像这样初始化映射器

var mapper = config.CreateMapper();  

然后代替静态映射器

Cutomer2 entity = Mapper.Map<Customer, Cutomer2>(request);

你像这样使用上面的 IMapper 界面

Cutomer2 entity = mapper.Map<Customer, Cutomer2>(request);

问题已解决。希望这有帮助