2016-01-20 134 views
3

我想映射具有子對象集合的同一類型的對象,並且發現忽略()應用於子對象上的屬性似乎是umm ...忽略!AutoMapper忽略子集合屬性

下面是一個演示問題的單元測試。

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); 

    } 

地圖後調用一個對象的ID屬性仍然是1,符合市場預期,但小孩B對象的ID屬性從11更改爲0。

爲什麼?

回答

6

AutoMapper 4.1.1中有幾個bug。

,第一是關於UseDestinationValuehttps://github.com/AutoMapper/AutoMapper/issues/568

第二個是關於嵌套集合:https://github.com/AutoMapper/AutoMapper/issues/934

可怕!解決方法是將您的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)); 

,並添加額外的映射電話:

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

    Mapper.Map(srcChild, destChild); 
} 

這將弄好的工作:

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

您可以在循環調用Mapper.Map