简体   繁体   中英

Set parent properties when mapping?

I have the following classes:

public class ParentDto
{
    public Guid Guid {get; set;}
    public IEnumerable<Child> Children {get; set;}

    public ParentDto() { Guid = Guid.NewGuid(); }
}

public class ChildDto
{
    public Guid Guid {get; set;}
    public Guid ParentGuid {get; set;}
    public IEnumerable<GrandChild> GrandChildren {get; set;}

    public ChildDto() { Guid = Guid.NewGuid(); }
}

public class GrandChildDto
{
    public Guid Guid {get; set;}
    public Guid ChildGuid {get; set;}

    public GrandChildDto() { Guid = Guid.NewGuid(); }
}

The mapping is simply:

Mapper.Initialize(cfg =>
{
  cfg.CreateMap<ParentModel, ParentDto>().ReverseMap();
  cfg.CreateMap<ChildModel, ChildDto>().ReverseMap();
  cfg.CreateMap<GrandChildModel, GrandChildDto>().ReverseMap();
});

Currently, I first do the mapping, then I do:

foreach (var child in parent.Children)
{
    child.ParentGuid = parent.Guid;

    foreach (var grandChild in child.GrandChildren)
    {
        grandChild.ChildGuid = child.Guid;
    }
}

This is because the Guid properties are only found in the DTO classes.

Is it possible to set the guids within the mapping configuration and avoid the foreach block?

AutoMapper does support execution code before and after map operations.

You can define them with code like this

cfg.CreateMap<Source, Target>()
   .AfterMap((src, dest) => { .. }); 

But you probably can use this only when your DTOs are depending on the ancestor-generation - eg ParentDto contains ChildDTO. Else the items are independent from each other and using AutoMapper could be way more complex, than just using foreaches.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM