鉴于以下代码,为什么在映射阶段我一直遇到异常?两个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;
}
}
}
谢谢你, 斯蒂芬
答案 0 :(得分:8)
拉动源并将AutoMapper.Net4项目添加到控制台后,我能够诊断出问题。
当Jimmy删除Static版本然后通过我重新添加它时,引入了API,无论如何,现在使用新API的语法略有不同。下面是添加源代码时的例外情况,请注意这个与通过Nuget最初抛出的内容之间的区别?
throw new InvalidOperationException("Mapper not initialized. Call Initialize with appropriate configuration.");
这导致我回到GitHub上的Getting Started Docs,在那里我很快发现我没有像这样初始化映射器
var mapper = config.CreateMapper();
然后代替静态Mapper
Cutomer2 entity = Mapper.Map<Customer, Cutomer2>(request);
你可以像上面那样使用上面的IMapper接口
Cutomer2 entity = mapper.Map<Customer, Cutomer2>(request);
问题解决了。希望这有帮助