Automapper映射属性
本文关键字:属性 映射 Automapper | 更新日期: 2023-09-27 18:19:55
迁移到v2.0后,我发现了这个问题
我尝试这样的地图属性:
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
当您需要映射到没有无参数构造函数的目标类型时,需要使用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));