How to avoid circular references with AutoMapper?

后端 未结 1 786
情歌与酒
情歌与酒 2021-01-03 05:03

I have the following models (and corresponding DTOs):

public class Link
{
    public int Id {get; set;}
    public int FirstLinkId {get; set;}
    public int         


        
1条回答
  •  一生所求
    2021-01-03 05:55

    The way I would handle this is to create separate DTO objects for the children:

    public class Employee
    {
        public int Id {get; set;}
        public string Name { get; set; }
        public Employee Supervisor {get; set; }
    }
    public class EmployeeDto {
        public int Id {get; set;}
        public string Name { get; set; }
        public SupervisorDto Supervisor { get; set; }
    
        public class SupervisorDto {
            public int Id {get; set;}
            public string Name { get; set; }
        }
    }
    Mapper.CreateMap();
    Mapper.CreateMap();
    

    Don't let your DTOs be recursive/self-referential. Be explicit in your structure on how deep you want it to go.

    EF can't do recursive joins, you're only doing one level, so don't make your DTOs go nuts with infinitely deep relationships. Be explicit.

    0 讨论(0)
提交回复
热议问题