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

3

以下是给定的代码,请问为什么在映射阶段一直出现异常?这两个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;
        }
    }
}

谢谢,Stephen

引发异常的详细信息是什么? - lzcd
“Customer2”被标记为“partial”,那么这个类的其余部分在哪里? - Ian Mercer
1个回答

8
在拉取源代码并将AutoMapper.Net4项目添加到控制台后,我能够诊断出问题所在。
当Jimmy删除了Static版本,然后通过我重新添加时,API的引入让我感到惊讶,由于新API的语法有些不同。下面是在添加源代码时抛出的异常,请注意这与最初通过Nuget抛出的异常之间的差异。
throw new InvalidOperationException("Mapper not initialized. Call Initialize with appropriate configuration."); 

这导致我回到了GitHub上的入门文档,很快发现我没有像下面这样初始化映射器。

var mapper = config.CreateMapper();  

那么,如果不使用静态 Mapper ,

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

您可以像下面这样使用上述的IMapper接口:
Cutomer2 entity = mapper.Map<Customer, Cutomer2>(request);

问题已解决。希望这可以帮助到您。

2
如果您想使用静态的Mapper类,也可以直接使用Mapper.Initialize。 - Jimmy Bogard

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接