Automapper map child list with from same type

谁都会走 提交于 2019-12-11 04:58:30

问题


I have entities that may have children and their children may have children and so on... When I get database models all entities are OK with correct children and parent. But the problem comes when I want to map to view model: Is there any possible way to map models from database like this?

// database model code first
public class Tomato
{
    public int Id { get; set; }

    public string Name { get; set; }

    public int? ParentId { get; set; }

    public virtual Tomato Parent { get; set; }

    public ICollection<Tomato> Children { get; set; }
}

// mvc view model
public class TomatoViewModel
{
    public int Id { get; set; }

    public string Name { get; set; }

    public int? ParentId { get; set; }

    public ICollection<TomatoViewModel> Children { get; set; }
}

Configured configuration.CreateMap<Tomato, TomatoModel>() but throws an StackOverflowException when try to bind child elements. Tried with

configuration.CreateMap<Tomato, TomatoViewModel>().ForMember( t => t.Children,
                options => options.Condition(context => (context.SourceValue as Tomato).ParentId == this.Id));
// this.Id refers to TomatoViewModel.Id

Update: in my controller class:

var models = foodIngredientsService.GetAllTomatoes().Where(t => t.ParentId == null).To<TomatoModel>().ToList();

Second Question: how to use second overload of options.Condition(Func<TomatoModel, bool> func) ??


回答1:


Try this where you specify the child member mapping;

configuration.CreateMap<Tomato, TomatoViewModel>()
.ForMember(t => t.Children, options => options.MapFrom(source => source.Children));


来源:https://stackoverflow.com/questions/37785124/automapper-map-child-list-with-from-same-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!