Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Automapper to map a property of a collection 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 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?

like image 858
lambinator Avatar asked Oct 05 '11 18:10

lambinator


People also ask

Can AutoMapper map collections?

Polymorphic element types in collectionsAutoMapper supports polymorphic arrays and collections, such that derived source/destination types are used if found.

How do I use AutoMapper to list a map?

Once you have your types, and a reference to AutoMapper, you can create a map for the two types. Mapper. CreateMap<Order, OrderDto>(); The type on the left is the source type, and the type on the right is the destination type.

When should you not use AutoMapper?

If you have to do complex mapping behavior, it might be better to avoid using AutoMapper for that scenario. Reverse mapping can get very complicated very quickly, and unless it's very simple, you can have business logic showing up in mapping configuration.

Is AutoMapper faster than manual mapping?

Inside this article, it discusses performance and it indicates that Automapper is 7 times slower than manual mapping. This test was done on 100,000 records and I must say I was shocked.


1 Answers

Use a LINQ query to grab just the ChildIds:

.ForMember(d => d.ChildIds, o => o.MapFrom(s => s.Children.Select(c => c.ChildId).ToArray()));
like image 70
PatrickSteele Avatar answered Sep 20 '22 05:09

PatrickSteele