0

I'm trying to replace this manual mapping:

var group = new Group {
    Participants = family.Children.ToDictionary(child => $"{child.LastName}, {child.FirstName}", child =>
        new Participant
        {
            Class = child.Age,
        })
};

to using Mapster: var camp = new UnitMapper().Map(family).

But how do I make it do the Dictionary's mapping correctly?

These is what I currently have:

[Mapper]
public interface IUnitMapper {
    Group Map(Family family);
}

public class MappingRegistration : IRegister {
    public void Register(TypeAdapterConfig config) {
        config.NewConfig<Family, Group>()
            .Map(to => to.Participants, from => from.Children)
            ;
        
        config.NewConfig<Child, Participant>()
            .Map(to => to.Class, from => from.Age)
            ;
    }
}

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

public class Child {
    public string FirstName { get; init; }
    public string LastName { get; init; }
    public int Age { get; init; }
}

public class Group {
    public IDictionary<string, Participant> Participants { get; set; }
}

public class Participant {
    public int Class { get; set; }
}
Tar
  • 8,529
  • 9
  • 56
  • 127

1 Answers1

1

There is no default mapping from IEnumerable to IDictionary because IEnumerable is not implicitly converted to IDictionary. So you need to write a transformation code for your property explicitly using Map method:

public class MappingRegistration : IRegister 
{
    public void Register(TypeAdapterConfig config)
    {
        config
            .NewConfig<Family, Group>()
            .Map(to => to.Participants,
                from => from
                    .Children
                    .ToDictionary(child => $"{child.LastName}, {child.FirstName}", child => child.Adapt<Participant>()));
        
        config
            .NewConfig<Child, Participant>()
            .Map(to => to.Class, from => from.Age);
    }
}
Vadim Martynov
  • 8,602
  • 5
  • 31
  • 43