如何忽略AutoMapper映射中的属性属性?

编程入门 行业动态 更新时间:2024-10-28 04:30:59
本文介绍了如何忽略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()参考得到修正!

推荐答案

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

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

更多推荐

如何忽略AutoMapper映射中的属性属性?

本文发布于:2023-11-09 10:45:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1572168.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   AutoMapper

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!