Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping Lists using Automapper

I have the classes:

public class Person{ /* Props here */ }

public class PersonViewModel { /* Props here */ }

Then the list:

List<Person> people = new List<Person>();
List<PersonViewModel> peopleVM = Mapper
                                .MapList<Person, PersonViewModel>(people); //Problem here.

What is the correct way to do this?

like image 847
Shawn Mclean Avatar asked Apr 08 '11 01:04

Shawn Mclean


People also ask

How do I use AutoMapper to list a map?

How do I use AutoMapper? First, you need both a source and destination type to work with. The destination type's design can be influenced by the layer in which it lives, but AutoMapper works best as long as the names of the members match up to the source type's members.

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.


2 Answers

Mapper.CreateMap<Person, PersonViewModel>();
peopleVM = Mapper.Map<List<Person>, List<PersonViewModel>>(people);
Mapper.AssertConfigurationIsValid();

From Getting Started:

How do I use AutoMapper?

First, you need both a source and destination type to work with. The destination type's design can be influenced by the layer in which it lives, but AutoMapper works best as long as the names of the members match up to the source type's members. If you have a source member called "FirstName", this will automatically be mapped to a destination member with the name "FirstName". AutoMapper also supports Flattening, which can get rid of all those pesky null reference exceptions you might encounter along the way.

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. To perform a mapping, use the Map method.

OrderDto dto = Mapper.Map<Order, OrderDto>(order);
like image 90
Derek Beattie Avatar answered Oct 23 '22 22:10

Derek Beattie


Another Solution

List<Person> people = new List<Person>();
List<PersonViewModel> peopelVM;
peopelVM = people.Select(Mapper.Map<Person, PersonViewModel>);

And in the Automapper config

Mapper.CreateMap<Person, PersonViewModel>();
like image 27
Ram Avatar answered Oct 23 '22 20:10

Ram