迁移到v2.0后,我发现了这个问题
我尝试这样的map属性:
public class SurveyFormView
{
public MultiSelectList Statistics { get; set; }
}
public class SurveyForm
{
ICollection<Statistic> statistics = new List<Statistic>();
public virtual ICollection<Statistic> Statistics
{
get { return statistics; }
set { statistics = value; }
}
}
Mapper.CreateMap<SurveyForm, SurveyFormView>().
ForMember(x => x.Statistics,
m =>
m.MapFrom(x => new MultiSelectList(x.Statistics))).
当我使用映射时:model = Mapper.Map<SurveyForm, SurveyFormView>(item);
我明白了:
[ArgumentException: Type 'System.Web.Mvc.MultiSelectList' does not have a default constructor]
System.Linq.Expressions.Expression.New(Type type) +2741878
AutoMapper.<>c__DisplayClass1.<CreateCtor>b__0(Type t) in c:\dev\AutoMapper\src\AutoMapper\Internal\DelegateFactory.cs:142
System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory) +72
AutoMapper.DelegateFactory.CreateCtor(Type type) in c:\dev\AutoMapper\src\AutoMapper\Internal\DelegateFactory.cs:140
AutoMapper.Mappers.ObjectCreator.CreateObject(Type type) in c:\dev\AutoMapper\src\AutoMapper\Mappers\ObjectCreator.cs:47
AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.CreateObject(ResolutionContext context) in c:\dev\AutoMapper\src\AutoMapper\MappingEngine.cs:362
AutoMapper.Mappers.EnumerableMapperBase`1.CreateDestinationObject(ResolutionContext context, Type destinationElementType, Int32 count, IMappingEngineRunner mapper) in c:\dev\AutoMapper\src\AutoMapper\Mappers\EnumerableMapperBase.cs:64
AutoMapper.Mappers.EnumerableMapperBase`1.Map(ResolutionContext context, IMappingEngineRunner mapper) in c:\dev\AutoMapper\src\AutoMapper\Mappers\EnumerableMapperBase.cs:21
AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.Map(ResolutionContext context) in c:\dev\AutoMapper\src\AutoMapper\MappingEngine.cs:303
答案 0 :(得分:0)
当您需要映射到没有无参数构造函数的目标类型时,您需要使用ConstructUsing
而不是MapFrom
:
Mapper.CreateMap<ICollection<Statistic>, MultiSelectList>()
.ConstructUsing(c => new MultiSelectList(c));
Mapper.CreateMap<SurveyForm, SurveyFormView>();
如果您将源集合注册为IEnumerable
:
Mapper.CreateMap<IEnumerable, MultiSelectList>()
.ConstructUsing(c => new MultiSelectList(c));