本文介绍了AutoMapper:PreserveReferences和MaxDepth有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点困惑.我找不到PreserveReferencesMaxDepth之间的区别.

I'm a little bit confused. I can't find out the difference between PreserveReferences and MaxDepth.

假设我们具有以下DTO和模型.

Let's suppose we have the following DTOs and models.

public class PersonEntity
{
    public PersonEntity InnerPerson { get; set; }
}

public class PersonModel
{
    public PersonModel InnerPerson { get; set; }
}

如文档中所述:

我的映射:

cfg.CreateMap<PersonModel, PersonEntity>().MaxDepth(1);
cfg.CreateMap<PersonEntity, PersonModel>();

程序:

var personModel = new PersonModel();
personModel.InnerPerson = personModel;
var entity = Mapper.Map<PersonEntity>(personModel);

那是我期望得到的:

那是我真正得到的:

我可以同时使用它们(PreserveReferencesMaxDepth)来解析循环引用,但是我看不出有什么区别.什么时候应该在MaxDepth方法中使用不同数量的深度?那么,有人可以提供吗?提前致谢.

I can use both of them (PreserveReferences and MaxDepth) for resolving circular references, but I don't see the difference. When I should use different number of depth in the MaxDepth method? So, could someone provide it? Thanks in advance.

推荐答案

MaxDepth在运行时不考虑对象值.在映射树的深度达到配置的值之后,它只是停止映射.

MaxDepth doesn't consider object values at runtime. It simply stops mapping after the depth of the mapping tree reaches the configured value.

PreserveReferencesProjectTo没有帮助,MaxDepth对.如果通过Map以某种方式,您有一个映射树可能会溢出堆栈,但是对象实例没有重复,则PreserveReferences不会有帮助,而MaxDepth会.

PreserveReferences doesn't help with ProjectTo, MaxDepth does. If somehow, with Map, you have a mapping tree that might overflow the stack, but objects instances are not duplicated, then PreserveReferences won't help, MaxDepth will.

MaxDepth是可预测的,它停止在硬编码值上,PreserveReferences仅在复制对象实例时停止.

MaxDepth is predictable, it stops at a hardcoded value, PreserveReferences stops only when an object instance is duplicated.

这篇关于AutoMapper:PreserveReferences和MaxDepth有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 15:36