I’m having a problem with one of my automapping configurations that I can’t seem to solve.
I have an entity of type contact and I’m trying to map a list of these to a dictionary. However, the mapping just doesn’t do anything. The source dictionary remains empty. Can anyone offer any suggestions?
Below is a simplified version of the Contact type
public class Contact
{
public Guid Id { get; set ;}
public string FullName { get; set; }
}
My automapping configuration looks as follows
Mapper.CreateMap<Contact, KeyValuePair<Guid, string>>()
.ConstructUsing(x => new KeyValuePair<Guid, string>(x.Id, x.FullName));
And my calling code looks as follows
var contacts = ContactRepository.GetAll(); // Returns IList<Contact>
var options = new Dictionary<Guid, string>();
Mapper.Map(contacts, options);
The documentation is very sketchy on the AutoMapper website. From what I can tell, the second parameter in
Mapper.Mapis used only to determine what type the return value should be, and is not actually modified. This is because it allows you to perform dynamic mapping based on an existing object whose type is only known at runtime instead of hard-coding a type in the generics.So the problem in your code is that you are not making use of the return value of
Mapper.Map, which actually contains the final converted object. Here is a modified version of your code that I’ve tested and correctly returns the converted objects as you expect.Although it would be more efficient to take advantage of the generic version instead of constructing an unnecessary object just to specify the type:
Here is a working code sample that can be run in LinqPad (an assembly reference to AutoMapper.dll is needed to run the sample.)
Hope this helps!