How mapping many to many with automapper

asp.net-mvc automapper c# dto entity-framework-6

Question

I have many to many relation for tables functions and roles and I have association table RolesFunctions. In the RolesFunctions I have row id ( IdFunctions and IdRoles Both its a prime key). the problem is when I map function with functionDTO and roles with rolesDTO with AutoMapper I have this error "An unhandled exception of type 'System.StackOverflowException' occurred in AutoMapper.dll. Make sure you do not have an infinite loop or infinite recursion."

my mapping :

CreateMap<Function, FunctionTDTO>().ReverseMap();
CreateMap<Roles, RolesDTO>().ReverseMap();

How automapper map many to many relationship ?

function classe

public class Functions
    {
        public Functions()
        {
            this.Roles = new HashSet<Roles>();
        }
        public int Id { get; set; }
        public string Description { get; set; }
        public virtual ICollection<Roles> Roles { get; set; }
    }

function DTO

public class FunctionsDTO
    {
        public int Id { get; set; }
        public string Description { get; set; }
        public virtual ICollection<RolesDTO> Roles { get; set; }
    }

Role classe

public class Roles
    {
        public Roles()
        {
            this.Functions = new HashSet<Functions>();
        }
        public int Id { get; set; }
        public string Libelle { get; set; }
        public virtual ICollection<Functions> Functions { get; set; }
    }

RoleDTO classe

public class RolesDTO
    {
        public int Id { get; set; }
        public string Libelle { get; set; }
        public virtual ICollection<FunctionsDTO> Functions { get; set; }
    }
1
0
2/7/2017 10:07:58 AM

Popular Answer

It is not a good practice to have reference in one DTO to second DTO because it cause many troubles (this, for example). You should make your DTOs based on your use case. For example in:

public class FunctionsDTO
{
    public int Id { get; set; }
    public string Description { get; set; }
    public virtual ICollection<RolesDTO> Roles { get; set; }
}

When you only need to use Roles.Libelle (for example in displaying or creating), you should make for example this DTO:

public class FunctionsCreateDTO
{
    public int Id { get; set; }
    public string Description { get; set; }
    public virtual ICollection<string> RoleLibelles { get; set; }
}

And then just change your Mapping.

0
2/7/2017 10:17:48 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow