0

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

2
  • I just installed Automapper 9.0.0 to .NET Framework WinForms project, copied your code, changed the configuration code to use MapperConfiguration, ran it, and configuration was created without errors. Please make a small test project and copy there only the code you feel is relevant and investigate from there. Commented Oct 7, 2019 at 9:23
  • @Dialecticus you can use this github project to see what I say, repo Commented Oct 7, 2019 at 10:01

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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)); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.