mapster

Mapster - How to map parent property to a list


I have a class with a property that is a list of child class.
I'm trying to map the Id of the parent class to a property in each item of the list.

Example (c#):

// Source.
public class Person
{
    public string Id { get; init; }
    public string FullName { get; init; }
    public List<PersonalAsset> PersonalAssets { get; init; }
}

public class PersonalAssets
{
    public string Descrip { get; init; }
    public decimal Value { get; init; }
}


// Dest.
public class PersonDto
{
    public string Id { get; init; }
    public string FullName { get; init; }
    public List<PersonalAssetDto> PersonalAssets { get; init; }
}

public class PersonalAssetsDto
{
    public string Id { get; init; }
    public string IdPerson { get; init; } // <= Person.Id. !!!
    public string Descrip { get; init; }
    public decimal Value { get; init; }
}

// Config.
config.NewConfig<Person, PersonDto>()
    .Map(dest => dest.PersonalAssets[???].IdPerson, src => src.Id); // <=========

How can I map Person.Id to PersonDto.PersonalAssets[].IdPerson?


Solution

  • config.NewConfig<Person, PersonDto>()
      .Map(dest => dest.PersonalAssets, src =>  
                new  List<PersonalAssetDto>{ new  
                      PersonalAssetsDto{ Id= src.Id}});