Using Automapper to map a property of a collection

2019-03-20 22:46发布

问题:

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 of Child.ChildId to ParentViewModel.ChildIds?

I've tried doing 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 an error saying it doesn't know how to convert a list of Child objects to an int16. Any suggestions?

回答1:

Use a LINQ query to grab just the ChildIds:

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