AutoMapper: What is the difference between PreserveReferences and MaxDepth?

主宰稳场 提交于 2019-11-30 21:06:16
Lucian Bargaoanu

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

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 is predictable, it stops at a hardcoded value, PreserveReferences stops only when an object instance is duplicated.

Thanks @Lucian Bargaoanu for the answer. I just want to add a simple example of MaxDepth.

I recently changed my DTOs and models.

public class SelfEntity
{
    public string Id { get; set; }
    public string Name { get; set; }
    public int Number;
    public SelfEntity InnerSelfEntity { get; set; }
}

public class SelfModel
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public int Number;
    public SelfModel InnerSelfModel { get; set; }
}

Mappings:

cfg.CreateMap<SelfModel, SelfEntity>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(x => x.Id.ToString()))
.MaxDepth(3);

Program:

SelfModel firstSelfModel = new SelfModel();
SelfModel prev = firstSelfModel;

for (int i = 0; i < 100; i++)
{
   SelfModel newModel = new SelfModel
   {
      Id = Guid.NewGuid(),
      Name = "Test name" + i.ToString(),
      Number = i
   };

   prev.InnerFirstSelf = newModel;
   prev = newModel;
}

var entity = Mapper.Map<FirstSelfEntity>(firstSelfModel);

Starts from the 3-th level of depth we will get null for the InnerSelfModel.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!