简体   繁体   English

如何使用自动映射器将多对多映射

[英]How mapping many to many with automapper

I have many to many relation for tables functions and roles and I have association table RolesFunctions. 我对表功能和角色有很多关系,并且我与关联表RolesFunctions相关。 In the RolesFunctions I have row id ( IdFunctions and IdRoles Both its a prime key). 在RolesFunctions中,我具有行ID(IdFunctions和IdRoles两者都是主键)。 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." 问题是,当我将具有functionDTO的功能和具有RoleDTO的角色与AutoMapper进行映射时,出现此错误“ AutoMapper.dll中发生了'System.StackOverflowException类型的未处理的异常。请确保您没有无限循环或无限递归。”

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 功能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 RoleDTO类

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

It is not a good practice to have reference in one DTO to second DTO because it cause many troubles (this, for example). 在一个DTO中引用第二个DTO并不是一个好习惯,因为这会引起很多麻烦(例如,这会引起麻烦)。 You should make your DTOs based on your use case. 您应该根据用例制作DTO。 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: 当只需要使用Roles.Libelle时(例如在显示或创建时),则应使用以下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. 然后只需更改您的映射。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM