Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have an entity:

public class Tag {     public int Id { get; set; }     public string Word { get; set; }     // other properties...     // and a collection of blogposts:     public ICollection<Post> Posts { get; set; } } 

and a model:

public class TagModel {     public int Id { get; set; }     public string Word { get; set; }     // other properties...     // and a collection of blogposts:     public int PostsCount { get; set; } } 

and I query the entity like this (by EF or NH):

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

Now, how can I map the tagsAnon (as an anonymous object) to a collection of TagModel (e.g. ICollection<TagModel> or IEnumerable<TagModel>)? Is it possible?

like image 764
amiry jd Avatar asked Mar 09 '12 18:03

amiry jd


People also ask

Does AutoMapper map both ways?

Yes, or you can call CreateMap<ModelClass, ViewModelClass>(). ReverseMap() .

How do you initialize an anonymous object?

You create anonymous types by using the new operator together with an object initializer. For more information about object initializers, see Object and Collection Initializers. The following example shows an anonymous type that is initialized with two properties named Amount and Message .

How does AutoMapper work in C#?

AutoMapper in C# is a library used to map data from one object to another. It acts as a mapper between two objects and transforms one object type into another. It converts the input object of one type to the output object of another type until the latter type follows or maintains the conventions of AutoMapper.


1 Answers

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(); 
like image 108
C. Augusto Proiete Avatar answered Sep 22 '22 12:09

C. Augusto Proiete