How to map multiple entities to one class in Mapster

178 Views Asked by At

In AutoMapper, we can map multiple entities to one, but can't impl in mapster. Automapper demo code:

Entity:

var users = await _userManager.Users
            .AsNoTracking()
            .ProjectTo<UserDto>(new { roles = _roleManager.Roles })              
            .ToListAsync();

AutoMapper config:

IQueryable<IdentityRole> roles = null;
        CreateMap<User, UserDto>()
            .ForMember(x => x.Roles, opt => 
                opt.MapFrom(src => 
                    src.Roles
                        .Join(roles, a => a.RoleId, b => b.Id, (a, b) => b.Name)
                        .ToList()
                )
            );

There is no parameter in Mapster Querable.ProjectTo() method. Who can help me see what I should do? Thanks.

1

There are 1 best solutions below

0
On

if I understand your question correctly, you are trying to map objects from multiple sources. Mapster supports this operation. From the Mapster GitHub repo:

public class SubDto
{
    public string Extra { get; set; }
}

public class Dto
{
    public string Name { get; set; }
    public SubDto SubDto { get; set; }
}

public class Poco
{
    public string Name { get; set; }
    public string Extra { get; set; }
}

If you want to map SubDto and Dto to Poco, you can use the following config:

TypeAdapterConfig<(SubDto, Dto), Poco>.NewConfig()
    .Map(dest => dest, src => src.Item1)
    .Map(dest => dest, src => src.Item2);

Hope, it helps!