Home > Net >  C# AutoMapper simplification
C# AutoMapper simplification

Time:02-20

Is there any way to simplify mapping? I wouldn't like to write src.Accounts.First().UserInfo accessing several times. It would be nice to put it in a separate variable. How to do it?

CreateMap<Test, TestDto>()
    .ForMember(dst => dst.FirstName, opt => opt.MapFrom(src => src.Accounts.First().UserInfo.FirstName))
    .ForMember(dst => dst.LastName, opt => opt.MapFrom(src => src.Accounts.First().UserInfo.LastName))
    .ForMember(dst => dst.Email, opt => opt.MapFrom(src => src.Accounts.First().UserInfo.Email));

Thank you

CodePudding user response:

You can use IncludeMembers.

CreateMap<Test, TestDto>().IncludeMembers(src => src.Accounts.First().UserInfo);

https://docs.automapper.org/en/latest/Flattening.html#includemembers

CodePudding user response:

You can seek Custom Type Converters.

public class TestDtoTypeResolver : ITypeConverter<Test, TestDto>
{
    public TestDto Convert(Test source, TestDto destination, ResolutionContext context)
    {
        var userInfo = source.Accounts.First().UserInfo;
        return new TestDto
        {
            FirstName = userInfo.FirstName, 
            LastName = userInfo.LastName, 
            Email = userInfo.Email
        };
    }
}
CreateMap<Test, TestDto>()
    .ConvertUsing<TestDtoTypeResolver>();

Sample .NET Fiddle

  • Related