how to map an anonymous object to a class by AutoMapper?

Update 2019-07-31: CreateMissingTypeMaps is now deprecated in AutoMapper v8, and will be removed in v9.

Support for automatically created maps will be removed in version 9.0.
You will need to explicitly configure maps, manually or using
reflection. Also consider attribute mapping.


Update 2016-05-11: DynamicMap is now obsolete.

Now you need to create a mapper from a configuration that sets CreateMissingTypeMaps to true:

var tagsAnon = Tags
    .Select(t => new { t.Id, t.Word, PostsCount = t.Posts.Count })
    .ToList();

var config = new MapperConfiguration(cfg => cfg.CreateMissingTypeMaps = true);
var mapper = config.CreateMapper();

var tagsModel = tagsAnon.Select(mapper.Map<TagModel>)
    .ToList();

Yes, it is possible. You would have to use the DynamicMap<T> method of the Automapper’s Mapper class for each anonymous object you have. Something like this:

var tagsAnon = Tags
    .Select(t => new { t.Id, t.Word, PostsCount = t.Posts.Count() })
    .ToList();

var tagsModel = tagsAnon.Select(Mapper.DynamicMap<TagModel>)
    .ToList();

Leave a Comment