我有点困惑.我无法找出PreserveReferences和MaxDepth之间的区别.
假设我们有以下DTO和模型.
public class PersonEntity
{
public PersonEntity InnerPerson { get; set; }
}
public class PersonModel
{
public PersonModel InnerPerson { get; set; }
}
如文档中所述:
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);
这就是我期望得到的:
这就是我实际得到的:
我可以使用它们(PreserveReferences和MaxDepth)来解析循环引用,但我没有看到区别.什么时候我应该在MaxDepth方法中使用不同的深度?那么,有人能提供吗?提前致谢.
解决方法:
MaxDepth在运行时不考虑对象值.它只是在映射树的深度达到配置值后停止映射.
PreserveReferences对ProjectTo没有帮助,MaxDepth也没有.如果以某种方式,使用Map,您有一个可能会溢出堆栈的映射树,但是对象实例不会重复,那么PreserveReferences将无济于事,MaxDepth将会有所帮助.
MaxDepth是可预测的,它在硬编码值处停止,PreserveReferences仅在对象实例重复时停止.