Automapper map child list with from same type

1.3k views Asked by At

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

There are 1 answers

4
jimmy_b On

Try this where you specify the child member mapping;

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