Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper with nested child list

Tags:

I have two classes below:

public class Module {     public int Id { get; set; }     public string Name { get; set; }     public string ImageName { get; set; }     public virtual ICollection<Page> Pages { get; set; } }  public class ModuleUI {     public int Id { get; set; }     public string Text { get; set; }     public string ImagePath { get; set; }     public List<PageUI> PageUIs { get; set; } } 

The mapping must be like this:

Id -> Id Name -> Text ImageName -> ImagePath  Pages -> PageUIs 

How can I do this using Automapper?

like image 535
tobias Avatar asked Feb 22 '12 12:02

tobias


People also ask

Does AutoMapper map nested objects?

With both flattening and nested mappings, we can create a variety of destination shapes to suit whatever our needs may be.

Is AutoMapper faster than manual mapping?

Automapper is considerably faster when mapping a List<T> of objects on . NET Core (It's still slower on full . NET Framework).

What can I use instead of AutoMapper?

AutoMapper is one of the popular object-object mapping libraries with over 296 million NuGet package downloads. It was first published in 2011 and its usage is growing ever since. Mapster is an emerging alternative to AutoMapper which was first published in 2015 and has over 7.4 million NuGet package downloads.


1 Answers

You can use ForMember and MapFrom (documentation).
Your Mapper configuration could be:

Mapper.CreateMap<Module, ModuleUI>()     .ForMember(s => s.Text, c => c.MapFrom(m => m.Name))     .ForMember(s => s.ImagePath, c => c.MapFrom(m => m.ImageName))     .ForMember(s => s.PageUIs, c => c.MapFrom(m => m.Pages)); Mapper.CreateMap<Page, PageUI>(); 

Usage:

var dest = Mapper.Map<ModuleUI>(     new Module     {         Name = "sds",         Id = 2,         ImageName = "sds",         Pages = new List<Page>         {             new Page(),              new Page()         }     }); 

Result:

enter image description here

like image 183
nemesv Avatar answered Oct 14 '22 08:10

nemesv