Saleh Bagheri
Saleh Bagheri

Reputation: 434

Automapper: How to map one source to multiple destinations

I have the following sample entities:

public class User
{
    public string Username { get; set; }
    public string Password { get; set; }
    pubilc HashSet<UserRole> Roles { get; set; }
}

public class Role
{
    public string RoleName { get; set; }
    public HashSet<UserRole> Users { get; set; }
}

public class UserRole
{
    public int UserId { get; set; }
    public virtual User User { get; set; }
    public int RoleId { get; set; }
    public virtual Role Role { get; set; }
}

and the following Dtos:

public class UserModel
{
    public string Username { get; set; }
    public string Password { get; set; }
    pubilc HashSet<RoleModel> Roles { get; set; }
}

public class RoleModel
{
    public string RoleName { get; set; }
    public HashSet<UserModel> Users { get; set; }
}

with the following AutoMapper configuration:

CreateMap<User, UserModel>();

CreateMap<Role, RoleModel>();

CreateMap<UserRole, UserModel>()
    .ConstructUsing((src, ctx) => ctx.Mapper.Map<UserModel>(src.User));

CreateMap<UserRole, RoleModel>()
    .ConstructUsing((src, ctx) => ctx.Mapper.Map<RoleModel>(src.Role));

but this configuration causes the iis to stop without any error!

Is this configuration right for mapping one source into multiple destinations?

Github test project

Upvotes: 0

Views: 225

Answers (2)

Xueli Chen
Xueli Chen

Reputation: 12695

You could try to the following mapping :

public MapperConfig()
    {
        CreateMap<User, UserModel>();

        CreateMap<UserRole, RoleModel>()
            .ForMember(des=>des.RoleName,opt=>opt.MapFrom(src=>src.Role.RoleName));

        CreateMap<Role, RoleModel>();
        CreateMap<UserRole, UserModel>()
            .ForMember(des => des.Username, opt => opt.MapFrom(src => src.User.Username))
            .ForMember(des => des.Password, opt => opt.MapFrom(src => src.User.Password));

    }

Upvotes: 1

Baratali Qadamalizada
Baratali Qadamalizada

Reputation: 88

I'm not sure if this is good approach to use such a mapping or not. But the problem is for an infinite loop which occurs in the mapping (nested mapping maybe).

StackOverflowException

UserA

Following codes which are commented is the source of loop:

Loop Source

Upvotes: 1

Related Questions