Mapping between domain model and view model using IEnumerable

therefore my domain model has a property called Children , which returns the entire menu with the identifier of the current object. I want to create a view model and in the controller display the values ​​between them. Therefore, the Children property IEnumerable<MenuModel> and menu.Children is of type IEnumerable<MenuCache> . What would be the easiest way to do this? Do I need to scroll through all the children and add them manually to the current model and just repeat it for all levels?

Model:

 public class MenuModel { public int ID { get; set; } public string URL { get; set; } public int ParentID { get; set; } public IEnumerable<MenuModel> Children { get; set; } } 

Controller:

 using (var context = ww.WebObjs.WebDataContext.Get()) { var menu = context.MenuCaches.Where(x=> x.ID == 0).FirstOrDefault(); model = new MenuModel() { ID = menu.ID, URL = menu.Text, ParentID = menu.ParentID, Children = menu.Children // how do I get those children? }; } 
+4
source share
1 answer

You can use LINQ:

 using (var context = ww.WebObjs.WebDataContext.Get()) { var menu = context.MenuCaches.Where(x => x.ID == 0).FirstOrDefault(); model = new MenuModel() { ID = menu.ID, URL = menu.Text, ParentID = menu.ParentID, Children = menu.Children.Select(x => new MenuModel { Prop1 = x.Prop1, Prop2 = x.Prop2, // and so on ... }) }; } 

or AutoMapper , which I would highly recommend. Therefore, after determining the appropriate mappings, the action of your controller becomes much more readable:

 using (var context = ww.WebObjs.WebDataContext.Get()) { var menu = context.MenuCaches.Where(x => x.ID == 0).FirstOrDefault(); model = Mapper.Map<MenuCache, MenuModel>(menu); } 
+2
source

All Articles