c# - 如何在AutoMapper映射中忽略属性的属性?

标签 c# entity-framework automapper stack-overflow nullreferenceexception

对具有多对多关系的 PersonGroup 类进行成像。一个人有一个组列表,一个组有一个人列表。

Person 映射到 PersonDTO 时,出现堆栈溢出异常,因为 AutoMapper 无法处理 Person >群组>成员>群组>成员>...

这是示例代码:

public class Person
{
    public string Name { get; set; }
    public List<Group> Groups { get; set; }
}

public class Group
{
    public string Name { get; set; }
    public List<Person> Members { get; set; }
}

public class PersonDTO
{
    public string Name { get; set; }
    public List<GroupDTO> Groups { get; set; }
}

public class GroupDTO
{
    public string Name { get; set; }
    public List<PersonDTO> Members { get; set; }
}

当我使用 .ForMember 创建映射器时,执行的第一个映射器会抛出空引用异常

这是映射器的代码:

CreateMap<Person, PersonDTO>()
    .ForMember(x => x.Groups.Select(y => y.Members), opt => opt.Ignore())
    .ReverseMap();

CreateMap<Group, GroupDTO>()
    .ForMember(x => x.Members.Select(y => y.Groups), opt => opt.Ignore())
    .ReverseMap();

那么我错过了什么或做错了什么?当我删除 .ForMember 方法时,不再抛出空引用异常

更新:我真的想强调我的问题的要点如何忽略属性的属性。这段代码只是一个相当简单的例子。

更新2:这就是我修复它的方法,非常感谢Lucian-Bargaoanu

CreateMap<Person, PersonDTO>()
    .ForMember(x => x.Groups.Select(y => y.Members), opt => opt.Ignore())
    .PreserveReferences() // This is the solution!
    .ReverseMap();

CreateMap<Group, GroupDTO>()
    .ForMember(x => x.Members.Select(y => y.Groups), opt => opt.Ignore())
    .PreserveReferences() // This is the solution!
    .ReverseMap();

感谢 .PreserveReferences() 循环引用得到修复!

最佳答案

关于c# - 如何在AutoMapper映射中忽略属性的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45298110/

相关文章:

c# - 在 LINQ to Entities 中,您如何订购如下?

c# - 如何在 .Net Core 的 Web Api 中使用 AutoMapper?

c# - 在安装依赖项时使用 IoC 容器是不好的做法还是代码味道?

c# - 首先通过将类型作为参数传递来动态实例化 Entity Framework 数据库中的模型对象

c# - ASP.NET 移动应用程序通过请求简单的 GET 操作获取 "500 Internal Sever Error"

c# - 解析空格分隔文本的最佳方法

c# - 更改 ListView 列的列高

c# - 中等信任度的 MySql 数据实体 EF6

c# - 自动映射器性能

c# - 尝试使用 SELECT 方法在列表框中显示表数据