Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapper MaxDepth() method

In my project I have a one to many relationship from Client -> Projects. As such, in one of my views, I am trying to show all of the Projects that belong to that Client. So I have an IEnumerable<ProjectDetailsViewModel> that represents all of the clients projects.

The problem is that the ProjectDetailsViewModel has a ClientDetailsViewModel which then has an IEnumerable<ProjectDetailsViewModel> and so on and so forth creating an endless loop of identical entities.

Is this where it is appropriate to use the MaxDepth() method on that .ForMember()? If so, how do I use it in this case, and if not, what is the solution?

I have tried MaxDepth(1) on the Client and whilst this prevents the StackOverflow exception, it then doesn't hold any data in the view model for that client.

like image 547
ediblecode Avatar asked Jan 14 '13 13:01

ediblecode


1 Answers

The problem was that I explicitly called AutoMapper from with the AutoMapConfig as such:

.ForMember(x => x.Client, opt => opt.MapFrom(src =>
    AutoMapper.Mapper.Map<ClientDetailsViewModel>(src.Client)))

If I just define it as:

.ForMember(x => x.Client, opt => opt.MapFrom(src => src.Client))

AutoMapper will know to stop after 1 recursion, and as I already have a map from Client -> ClientDetailsViewModel there is no problem.

like image 135
ediblecode Avatar answered Sep 28 '22 07:09

ediblecode