Mapster and nonmatching member names

Viewed 285

When field names don't match, Mapster won't map. Fields are set to nulls or zeroes depending on type.

How do I use custom names for target attributes?

Ex.: How do I change SchoolClassTeacherName to just Name? Changing it in the code below and in class SchoolDTO gives me null as a result of mapping.

I've read the documentation but there is no answer. Please, help me. Thank you.

config.NewConfig<SchoolPoco, SchoolDTO>()
                .Map(dest => dest.SchoolClassTeacherName, 
                     src => src.School.Class.Teacher.Name)

I have this in my Startup.cs

            var typeAdapterConfig = TypeAdapterConfig.GlobalSettings;
            typeAdapterConfig.Scan(Assembly.GetExecutingAssembly());
            var mapperConfig = new Mapper(typeAdapterConfig);
            services.AddSingleton<IMapper>(mapperConfig);

I have mapping in a class

    public class ProjectMappingProfile : IRegister
    {
        void IRegister.Register(TypeAdapterConfig config)
           {
             // Mappings here
           }
    }
1 Answers

Use TypeAdapterConfig as described in documentation.

Make sure that School, Class, Teacher, Name properties is set.

Sample code:

using Mapster;

TypeAdapterConfig<DtoA, DtoB>
    .NewConfig()
    .Map(dest => dest.Main_Property, src => src.MainProperty)
    .Map(dest => dest.Inner_Property, src => src.InnerDto.InnerProperty);

DtoA a = new DtoA()
{
    MainProperty = "Hello",
    InnerDto = new InnerDto() { InnerProperty = "World" }
};
DtoB b = a.Adapt<DtoB>();


class DtoA
{
    public string MainProperty { get; set; }
    public InnerDto InnerDto { get; set; }
}

class InnerDto
{
    public string InnerProperty { get; set; }
}

class DtoB
{
    public string Main_Property { get; set; }
    public string Inner_Property { get; set; }
}


Result in b variable:

Result in b variable

Related