AutoMapper:避免使用MaxDepth进行无限递归吗?

时间:2019-10-11 16:14:02

标签: c# recursion automapper

我有以下简单的代码

    public class User
    {
        public List<UserGroup> UserGroups { get; set; }
        public string Name { get; set; }
    }

    public class UserGroup
    {
        public User User { get; set; }
        public Group Group { get; set; }
    }

    public class Group
    {
        public List<UserGroup> UserGroups { get; set; }
        public string Name { get; set; }
    }

    public class UserDto
    {
        public List<UserGroupDto> UserGroups { get; set; }
        public string Name { get; set; }
    }

    public class UserGroupDto
    {
        public UserDto User { get; set; }
        public GroupDto Group { get; set; }
    }

    public class GroupDto
    {
        public List<UserGroupDto> UserGroups { get; set; }
        public string Name { get; set; }
    }

    private static void TestAutoMapper()
    {
        var mapperCfg = new AutoMapper.MapperConfiguration(cfg =>
        {
            cfg.CreateMap<User, UserDto>().MaxDepth(1);
            cfg.CreateMap<UserGroup, UserGroupDto>().MaxDepth(1);
            cfg.CreateMap<Group, GroupDto>().MaxDepth(1);
        });
        var mapper = mapperCfg.CreateMapper();

        var user = new User { Name = "User1" };
        var group = new Group { Name = "Group1" };
        var userGroups = new List<UserGroup> { new UserGroup { User = user, Group = group } };
        user.UserGroups = userGroups;
        group.UserGroups = userGroups;

        var users = new List<User> { user };
        var usersDto = mapper.Map<IEnumerable<User>, IEnumerable<UserDto>>(users);
    }

但是我不能阻止无限递归,因为它保留了对象引用。

如何限制到仅第一个“已映射”实例?

示例:

UserDto->列表-> UserGrop->列表(空)

UserDto->列表-> UserDto(空)

谢谢。

1 个答案:

答案 0 :(得分:-1)

好的,这似乎是一个不好的模式实现。

我通过采用以下映射找到了解决问题的方法。

    private static void TestAutoMapper()
    {
        var mapperCfg = new AutoMapper.MapperConfiguration(cfg =>
        {
            cfg.CreateMap<User, UserDto>()
                .ForMember(dst => dst.UserGroups, opt => opt.Ignore())
            ;
            cfg.CreateMap<UserGroup, UserGroupDto>();
            cfg.CreateMap<Group, GroupDto>()
                .ForMember(dst => dst.UserGroups, opt => opt.Ignore())
            ;
        });
        var mapper = mapperCfg.CreateMapper();

        var user = new User { Name = "User1" };
        var group = new Group { Name = "Group1" };
        var userGroups = new List<UserGroup> { new UserGroup { User = user, Group = group } };
        user.UserGroups = userGroups;
        group.UserGroups = userGroups;

        var users = new List<User> { user };

        var usersDto = users.Select(u =>
        {
            var dto = mapper.Map<User, UserDto>(u);
            dto.UserGroups = mapper.Map<IEnumerable<UserGroup>, IEnumerable<UserGroupDto>>(u.UserGroups).ToList();

            return dto;
        });
    }