简体   繁体   中英

Automapper map property

After migrating to v2.0 I catch this issue

I try map property like this:

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))).

When I use mapping: model = Mapper.Map<SurveyForm, SurveyFormView>(item); I get:

[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

You need to use ConstructUsing instead of MapFrom when you need to map to destination types without parameterless constructor:

Mapper.CreateMap<ICollection<Statistic>, MultiSelectList>()
   .ConstructUsing(c => new MultiSelectList(c)); 
Mapper.CreateMap<SurveyForm, SurveyFormView>();

It will also work if you register the source collection as IEnumerable :

Mapper.CreateMap<IEnumerable, MultiSelectList>()
    .ConstructUsing(c => new MultiSelectList(c));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM