AutoMapper: What is the difference between PreserveReferences and MaxDepth?

I'm a little confused. I can not find out the difference between PreserveReferencesand MaxDepth.

Suppose we have the following DTOs and models.

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

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

As stated in the documentation:

Previously, AutoMapper could handle circular references, keeping track of what was mapped, and with each mapping, check the local hashtable of source / destination objects to see if the item was already mapped. It turns out that tracking is very expensive, and you need to choose to use PreserveReferences for circular maps to work. Alternatively, you can customize MaxDepth.

My mappings:

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

Program:

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

Here is what I expect to get:

enter image description here

Here is what I actually get:

enter image description here

(PreserveReferences MaxDepth) , . MaxDepth? - ? .

+4
2

MaxDepth . , .

PreserveReferences ProjectTo, MaxDepth. - Map , , , PreserveReferences , MaxDepth .

MaxDepth , , PreserveReferences .

+1

@Lucian Bargaoanu . MaxDepth.

DTO .

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; }
}

:

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

:

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);

3- , null InnerSelfModel.

PreserveReferences ProjectTo, MaxDepth . , Map, , , , PreserveReferences , MaxDepth .

0

Source: https://habr.com/ru/post/1693728/


All Articles