AutoMapper使用错误的构造函数 [英] AutoMapper using the wrong constructor
问题描述
今天,我使用AutoMapper v1.1将功能全面的应用程序升级为现在使用AutoMapper v2.1,并且遇到了一些以前版本中从未遇到过的问题.
Today I upgraded a fully functioning application using AutoMapper v1.1 to now use AutoMapper v2.1 and I am coming across some issues that I never encountered using the previous version.
这是我的代码从 Dto 映射到 Domain 对象
Here is an example of my code mapping back from Dto to Domain object
public class TypeOne
{
public TypeOne()
{
}
public TypeOne(TypeTwo two)
{
//throw ex if two is null
}
public TypeOne(TypeTwo two, TypeThree three)
{
//throw ex if two or three are null
}
public TypeTwo Two {get; private set;}
public TypeThree Three {get; private set;}
}
public class TypeOneDto
{
public TypeOneDto()
{
}
public TypeTwoDto Two {get; set;}
public TypeThreeDto Three {get; set;}
}
...
Mapper.CreateMap<TypeThreeDto, TypeThree>();
Mapper.CreateMap<TypeTwoDto, TypeTwo>();
Mapper.CreateMap<TypeOneDto, TypeOne>();
var typeOne = Mapper.Map<TypeOne>(typeOneDto);
但是,我在v2.1上遇到的第一个问题是,当其中一个args为null且应使用1个arg构造函数时,AutoMapper试图使用具有2个args的构造函数.
However the first problem I encountered with v2.1 was that AutoMapper was trying to use the constructor with 2 args when one of the args was null and should be using the 1 arg constructor.
然后我尝试使用
Mapper.CreateMap<TypeOneDto, TypeOne>().ConstructUsing(x => new TypeOne());
但是我一直遇到无法解决的模棱两可的调用"错误.
But I kept getting an 'Ambiguous Invocation' error that I couldn't resolve.
然后我尝试
Mapper.CreateMap<TypeOneDto, TypeOne>().ConvertUsing(x => new TypeOne());
并确实使用无参数构造函数成功创建TypeOne对象,但随后却无法设置私有setter属性.
and that did successfully create the TypeOne object using the parameterless constructor but then it failed to set the private setter properties.
我已经在AutoMapper网站上寻求帮助,并下载了源代码以使外观看起来不错,但由于篇幅很小的文档并不能理解,而且ConstructUsing的单元测试也不多.
I have looked for help on the AutoMapper website and downloaded the source code to have a good look but didn't get far with the little documentation about and there were not many unit tests for ConstructUsing.
我是否明显缺少我应该使用v2.1进行更改的问题?与v1.1相比,它发生了如此大的变化,我感到很惊讶.
Is there anything obvious I am missing that I should change with v2.1? I am surprised that it has changed so much from v1.1.
推荐答案
您只需要添加这是代码:
Mapper.CreateMap<TypeOneDto, TypeOne>().ConstructUsing(
(Func<ResolutionContext, TypeOne>) (r => new TypeOne()));
AutoMapper的当前版本如下所述:
Current version of AutoMapper works as described below:
-
按参数计数对目标类型的构造函数进行排序
Sorts destination type constructors by parameter count
destTypeInfo.GetConstructors().OrderByDescending(ci => ci.GetParameters().Length);
采用第一个构造函数,该构造函数的参数与源属性匹配(不检查空值).在您的情况下,它是带有两个参数的构造函数.
Takes first constructor which parameters match source properties (without any check for null value). In your case it is constructor with two parameters.
这篇关于AutoMapper使用错误的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!