AutoMapper:PreserveReferences和MaxDepth有什么区别? [英] AutoMapper: What is the difference between PreserveReferences and MaxDepth?

查看:147
本文介绍了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; }
}

如文档中所述:

以前,AutoMapper可以通过保持 跟踪已映射的内容,并在每个映射上检查本地 源/目标对象的哈希表,以查看该项目是否已经存在 映射.事实证明,这种跟踪非常昂贵,您需要 使用PreserveReferences选择启用圆形地图. 或者,您可以配置MaxDepth.

Previously, AutoMapper could handle circular references by keeping track of what was mapped, and on every mapping, check a local hashtable of source/destination objects to see if the item was already mapped. It turns out this tracking is very expensive, and you need to opt-in using PreserveReferences for circular maps to work. Alternatively, you can configure MaxDepth.

我的映射:

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有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆