Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper DynamicMap failing to map Lists of anonymous types

I have the following snippet of code.

var files = query.ToList();
var testFile = Mapper.DynamicMap<EftFileDto>(files.First());
var filesDto = Mapper.DynamicMap<List<EftFileDto>>(files);

testFile has a properly mapped value, but filesDto is empty.

It appears dynamicMap works on individual items, but not lists?

files is a List of anonymous objects.

EDIT: It doesn't work if I use Arrays either. I can get it to work, but ...

        var filesDto = query.Select(Mapper.DynamicMap<EftFileDto>).ToList();
like image 491
CaffGeek Avatar asked Jan 31 '13 16:01

CaffGeek


1 Answers

In most mapping scenarios, we know the type we’re mapping to at compile time. In some cases, the source type isn’t known until runtime, especially in scenarios where I’m using dynamic types or in extensibility scenarios.

The DynamicMap call creates a configuration for the type of the source object passed in to the destination type specified. If the two types have already been mapped, AutoMapper skips this step (as I can call DynamicMap multiple times for this example).

Source: http://lostechies.com/jimmybogard/2009/04/15/automapper-feature-interfaces-and-dynamic-mapping/

Shorter version: DynamicMap is the same as calling CreateMap then Map.

Some dummy Person class

public class Person
    {
        public string Name { get; set; }
        public string Surname { get; set; }
        public int Age { get; set; }
    }

Lets say you have a list of Persons.

var persons = new List<Person>();
for (int i = 0; i < 100; i++)
{
      persons.Add(new Person { 
                Name = String.Format("John {0}", i), 
                Surname = String.Format("Smith {0}", i), 
                Age = i });
}

Then you make a select on persons adding a new property.

var anonymousTypes = persons.Select(p => new { 
            p.Name, 
            p.Surname, 
            FullName = String.Format("{0}, {1}", p.Surname,p.Name) }).ToList();

To get properly mapped the first person

var testFile = Mapper.DynamicMap<Person>(anonymousTypes.First()); 

To get properly mapped all persons you would use

var testFiles  = anonymousTypes.Select(Mapper.DynamicMap<Person>).ToList(); 
like image 84
Matija Grcic Avatar answered Oct 08 '22 04:10

Matija Grcic