简体   繁体   English

AutoMapper MaxDepth()方法

[英]AutoMapper MaxDepth() method

In my project I have a one to many relationship from Client -> Projects . 在我的项目中,我与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. 所以我有一个代表所有客户端项目的IEnumerable<ProjectDetailsViewModel>

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. 问题是ProjectDetailsViewModel有一个ClientDetailsViewModel ,然后有一个IEnumerable<ProjectDetailsViewModel>等等,创建了一个无限循环的相同实体。

Is this where it is appropriate to use the MaxDepth() method on that .ForMember()? 这是否适合在.ForMember()上使用MaxDepth()方法? 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. 我在Client上尝试过MaxDepth(1),虽然这可以防止StackOverflow异常,但它不会在该客户端的视图模型中保存任何数据。

The problem was that I explicitly called AutoMapper from with the AutoMapConfig as such: 问题是我使用AutoMapConfig显式调用了AutoMapper:

.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. AutoMapper将知道在1次递归后停止,并且因为我已经有来自Client -> ClientDetailsViewModel的地图,所以没有问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM