Mapping Lists using Automapper

120,693

Solution 1

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);

Solution 2

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>();

Solution 3

If you're using IQueryable lists here (from EF or NH, for example) you can use the AutoMapper.IQueryableExtensions methods, Project() and To().

This is my first time with AutoMapper, but I'm succeeding by creating a map for just the model:

Mapper.CreateMap<Person, PersonViewModel>();
Mapper.AssertConfigurationIsValid();

And then using the IQueryableExtension methods Project() and To():

using AutoMapper.QueryableExtensions;
...

IQueryable<Person> people = new List<Person>().AsQueryable(); //actually from ORM
IQueryable<PersonViewModel> peopleVM = people.Project().To<PersonViewModel>();

Solution 4

In core 1.1 this extension might work:

public static List<TDestination> MapList<TSource, TDestination>(this IMapper mapper, List<TSource> source)
        {
            return source.Select(x => mapper.Map<TDestination>(x)).ToList();
        }

Solution 5

Another Solution

mapper.Map<IEnumerable<PersonViewModel>>(people);
Share:
120,693

Related videos on Youtube

Shawn Mclean
Author by

Shawn Mclean

:)

Updated on July 05, 2022

Comments

  • Shawn Mclean
    Shawn Mclean almost 2 years

    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?

  • Shawn Mclean
    Shawn Mclean about 13 years
    Do I need to use CreateMap? I've been using automapper without it and it works.
  • Derek Beattie
    Derek Beattie about 13 years
    Probably not as long as property names match and it doesn't need to convert anything. You can use create map if property names don't match or you want to ignore properties etc.
  • Shawn Mclean
    Shawn Mclean about 13 years
    this didn't work. I used that same code and got this error: Trying to map System.Collections.Generic.List1[[Econo.Domain.Person, Econo.Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] to System.Collections.Generic.List1[[Econo.Web.ViewModels.Perso‌​nViewModel, Econo.Web, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]. Exception of type 'AutoMapper.AutoMapperMappingException' was thrown.`
  • Derek Beattie
    Derek Beattie about 13 years
    Try adding the create map. You can also do Mapper.AssertConfigurationIsValid(); after the create. Usually you put all your creates in bootstrapper or startup function. AutoMapper also supports profiles.
  • Shawn Mclean
    Shawn Mclean about 13 years
    @Derek Beattie It runs successfully now but my count is 0. So peopleVM.Count is 0. Any idea why it didn't copy over the items?
  • Derek Beattie
    Derek Beattie about 13 years
    How is List<Person> People populated?
  • Shawn Mclean
    Shawn Mclean about 13 years
    wow, you were actually right from the begininng. If only I didn't modify the CreateMap to use list.
  • Derek Beattie
    Derek Beattie about 13 years
    I still do that and stare at it trying to figure out what's wrong.
  • doganak
    doganak almost 12 years
    Is there any short method to create mapping to both direction to each other? Mapper.Map<List<Person>, List<PersonViewModel>>(person) and Mapper.Map<List<PersonViewModel> ,List<Person>>(person)
  • WholeLifeLearner
    WholeLifeLearner almost 8 years
    @doganak Mapper.Map<List<Person>, List<PersonViewModel>>(person).ReverseMap()
  • Alexei - check Codidact
    Alexei - check Codidact over 7 years
    I find this answer the most useful / elegant. However, Project() is now deprecated and should be replaced with ProjectTo().