Using Automapper to map a collection property to an array of primitives

Given the following set of classes:

class Parent { string Name { get; set; } List<Child> children { get; set; } } class Child { short ChildId { get; set; } string Name { get; set; } } class ParentViewModel { string Name { get; set; } short[] ChildIds { get; set; } } 

When i call

 Mapper.Map<Parent, ParentViewModel>(vm); 

Is it possible to get AutoMapper to translate the list Child.ChildId into ParentViewModel.ChildIds ?

I tried to do something like this:

 Mapper.CreateMap<Child, short>() .FromMember(dest => dest, opt => opt.MapFrom(src => src.ChildId)); Mapper.CreateMap<Parent, ParentViewModel>() .FromMember(dest => dest.ChildIds, opt => opt.MapFrom(src => new[] {src.children})); 

But I get a message that he does not know how to convert the list of child objects to int16. Any suggestions?

+6
source share
1 answer

Use the LINQ query to capture only children:

 .ForMember(d => d.ChildIds, o => o.MapFrom(s => s.Children.Select(c => c.ChildId).ToArray())); 
+12
source

Source: https://habr.com/ru/post/898695/


All Articles