鉴于下面的代码如下,为什么我在映射阶段一直遇到异常?两个DTO真的那么不同吗?这是抛出异常的符号服务器pdb的代码行.
throw new AutoMapperMappingException(context, "Missing type map configuration or unsupported mapping.");
Run Code Online (Sandbox Code Playgroud)
真正让我感到害怕的是@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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢你,斯蒂芬
拉动源并将AutoMapper.Net4项目添加到控制台后,我能够诊断出问题.
当Jimmy删除Static版本然后通过我重新添加它时,引入了API,无论如何,现在使用新API的语法略有不同.下面是添加源代码时的例外情况,请注意这个与通过Nuget最初抛出的内容之间的区别?
throw new InvalidOperationException("Mapper not initialized. Call Initialize with appropriate configuration.");
Run Code Online (Sandbox Code Playgroud)
这导致我回到GitHub上的入门文档,在那里我很快发现我没有像这样初始化映射器
var mapper = config.CreateMapper();
Run Code Online (Sandbox Code Playgroud)
而不是静态Mapper
Cutomer2 entity = Mapper.Map<Customer, Cutomer2>(request);
Run Code Online (Sandbox Code Playgroud)
你可以像上面那样使用上面的IMapper接口
Cutomer2 entity = mapper.Map<Customer, Cutomer2>(request);
Run Code Online (Sandbox Code Playgroud)
问题解决了.希望这可以帮助
| 归档时间: |
|
| 查看次数: |
5267 次 |
| 最近记录: |