[英]AutoMapper Ignore on child collection property
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! 我试图映射具有子对象集合的相同类型的对象,并发现应用于子对象的属性的Ignore()似乎是umm ...忽略!
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);
}
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. 在Map调用之后,A对象的Id属性仍然是1,正如预期的那样,但子B对象的Id属性从11更改为0。
Why? 为什么?
There are several bugs in AutoMapper 4.1.1. AutoMapper 4.1.1中有几个错误。
First is about UseDestinationValue
: https://github.com/AutoMapper/AutoMapper/issues/568 首先是关于UseDestinationValue
: https : //github.com/AutoMapper/AutoMapper/issues/568
Second is about nested collections: https://github.com/AutoMapper/AutoMapper/issues/934 其次是关于嵌套集合: https : //github.com/AutoMapper/AutoMapper/issues/934
Horrifying! 可怕! The workaround is to map your B
instances directly: 解决方法是直接映射您的B
实例:
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));
and add additional mapping calls: 并添加其他映射调用:
Mapper.Map(src, dest);
Mapper.Map(src.Children.First(), dest.Children.First()); //example!!!
You may call Mapper.Map
in cycle: 您可以在循环中调用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);
}
This will make things work right. 这将使事情正常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.