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