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?
Polymorphic element types in collectionsAutoMapper supports polymorphic arrays and collections, such that derived source/destination types are used if found.
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.
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.
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.
Use a LINQ query to grab just the ChildIds:
.ForMember(d => d.ChildIds, o => o.MapFrom(s => s.Children.Select(c => c.ChildId).ToArray()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With