AutoMapper忽略子集合属性

编程入门 行业动态 更新时间:2024-10-28 16:18:29
本文介绍了AutoMapper忽略子集合属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试映射具有子对象集合的相同类型的对象,并且发现应用于子对象上属性的Ignore()似乎很...忽略了!

I am trying to map object's of the same type which have a collection of child objects and am finding that Ignore() applied to properties on the child object seem to be umm... ignored!

这是一个演示该问题的单元测试.

Here's a unit test which demonstrates the problem.

class A { public int Id { get; set; } public string Name { get; set; } public ICollection<B> Children { get; set; } } class B { public int Id { get; set; } public string Name { get; set; } } [TestClass] public class UnitTest1 { [TestInitialize()] public void Initialize() { Mapper.CreateMap<A, A>() .ForMember(dest => dest.Id, opt => opt.Ignore()); Mapper.CreateMap<B, B>() .ForMember(dest => dest.Id, opt => opt.Ignore()); } [TestMethod] public void TestMethod1() { A src = new A { Id = 0, Name = "Source", Children = new List<B> { new B { Id = 0, Name = "Child Src" } } }; A dest = new A { Id = 1, Name = "Dest", Children = new List<B> { new B { Id = 11, Name = "Child Dest" } } }; Mapper.Map(src, dest); }

在Map调用之后,A对象的Id属性仍为1,这与预期的一样,但是子B对象的Id属性从11更改为0.

After the Map call the A object's Id property is still 1, as expected, but child B object's Id property is changed from 11 to 0.

为什么?

推荐答案

AutoMapper 4.1.1中有几个错误.

There are several bugs in AutoMapper 4.1.1.

首先是关于UseDestinationValue: github/AutoMapper/AutoMapper/Issues/568

第二个关于嵌套集合: github/AutoMapper/AutoMapper/issues/934

Second is about nested collections: github/AutoMapper/AutoMapper/issues/934

令人恐惧!解决方法是直接映射您的B实例:

Horrifying! The workaround is to map your B instances directly:

Mapper.CreateMap<A, A>() .ForMember(dest => dest.Id, opt => opt.Ignore()) .ForMember(dest => dest.Children, opt => opt.Ignore()); Mapper.CreateMap<B, B>() .ForMember(dest => dest.Id, opt => opt.Condition((ResolutionContext src) => false));

并添加其他映射调用:

Mapper.Map(src, dest); Mapper.Map(src.Children.First(), dest.Children.First()); //example!!!

您可以循环调用Mapper.Map:

for (int i = 0; i < src.Children.Count; i++) { var srcChild = src.Children[i]; var destChild = dest.Children[i]; Mapper.Map(srcChild, destChild); }

这将使事情正常进行.

更多推荐

AutoMapper忽略子集合属性

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

发布评论

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

>www.elefans.com

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