92

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?

SteveC
  • 15,808
  • 23
  • 102
  • 173
Shawn Mclean
  • 56,733
  • 95
  • 279
  • 406

6 Answers6

112
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);
InteXX
  • 6,135
  • 6
  • 43
  • 80
Derek Beattie
  • 9,429
  • 4
  • 30
  • 44
  • 3
    Do I need to use CreateMap? I've been using automapper without it and it works. – Shawn Mclean Apr 08 '11 at 01:51
  • 1
    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. – Derek Beattie Apr 08 '11 at 01:56
  • this didn't work. I used that same code and got this error: Trying to map System.Collections.Generic.List`1[[Econo.Domain.Person, Econo.Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] to System.Collections.Generic.List`1[[Econo.Web.ViewModels.PersonViewModel, Econo.Web, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]. Exception of type 'AutoMapper.AutoMapperMappingException' was thrown.` – Shawn Mclean Apr 08 '11 at 03:41
  • 1
    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. – Derek Beattie Apr 08 '11 at 03:58
  • @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? – Shawn Mclean Apr 08 '11 at 04:10
  • How is List People populated? – Derek Beattie Apr 08 '11 at 04:49
  • wow, you were actually right from the begininng. If only I didn't modify the CreateMap to use list. – Shawn Mclean Apr 08 '11 at 06:18
  • I still do that and stare at it trying to figure out what's wrong. – Derek Beattie Apr 08 '11 at 06:28
  • 1
    Is there any short method to create mapping to both direction to each other? `Mapper.Map, List>(person)` and `Mapper.Map ,List>(person)` – doganak Jul 23 '12 at 08:22
  • 2
    @doganak Mapper.Map, List>(person).ReverseMap() – WholeLifeLearner Aug 03 '16 at 11:49
  • @ShawnMclean So what was the problem? What was the beginning where Derek Beattie was right? Are your Automapper questions duplicates after all? – The incredible Jan Jun 29 '23 at 12:26
29

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>();
Ram
  • 15,908
  • 4
  • 48
  • 41
15

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>();
d219
  • 2,707
  • 5
  • 31
  • 36
Jerph
  • 4,572
  • 3
  • 42
  • 41
3

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();
        }
ruudj
  • 31
  • 2
3

Another Solution

mapper.Map<IEnumerable<PersonViewModel>>(people);
Ranga
  • 1,191
  • 12
  • 19
0

You could create an extension method to do something like this using existing mappings for individual items:

public static class AutoMapperExtensions
{
    public static List<TDestination> MapList<TSource, TDestination>(this IMapper mapper, List<TSource> source)
    {
        return mapper.Map<List<TDestination>>(source);
    }
}

Usage:

List<PersonViewModel> peopleVM = _mapper.MapList<PersonViewModel>(people);
garryp
  • 5,508
  • 1
  • 29
  • 41