如何忽略AutoMapper映射中的属性属性? [英] How to ignore property of property in AutoMapper mapping?

查看:1905
本文介绍了如何忽略AutoMapper映射中的属性属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

图像一个个人和一个类具有多对多关系。一个人有一个组的列表,一个组有一个人的列表。

Image a Person and a Group class with a many-to-many relationship. A person has a list of groups and a group has a list of people.

当映射 Person PersonDTO 我有一个堆栈溢出异常,因为AutoMapper无法处理 Person > > 成员> > 成员> ...

When mapping Person to PersonDTO I have a stack overflow exception because AutoMapper can't handle the Person>Groups>Members>Groups>Members>...

所以这里是示例代码:

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创建一个映射器时,第一个映射器执行时抛出一个空引用异常

When I use .ForMember in creating a mapper, the first mapper that gets executed throws a null reference exception.

这是映射器的代码:

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方法时,不再抛出空引用异常

So what am I missing or doing wrong? When I remove the .ForMember methods, the null reference exception is not thrown anymore.

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

UPDATE: I really want to emphasize the main point of my question is how to ignore a property of a property. This code is just a rather simple example.

更新2:这是我如何修复它,非常感谢 Lucian-Bargaoanu

UPDATE 2: This is how I fixed it, big thanks to 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()参考得到修正!

推荐答案

这应该只是工作。请参阅 https://github.com/AutoMapper/AutoMapper/wiki /5.0-Upgrade-Guide#circular-references 。还有一个公关待命的 https://github.com/AutoMapper/AutoMapper/pull/2233

This should just work. See https://github.com/AutoMapper/AutoMapper/wiki/5.0-Upgrade-Guide#circular-references. There is also a PR pending https://github.com/AutoMapper/AutoMapper/pull/2233.

这篇关于如何忽略AutoMapper映射中的属性属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆