2017-02-22 25 views
0

我的例子:Automapper失敗用於與其中的物品使用ConvertUsing <集合對象>()

class BoxVM { 
    int BoxId {get;set;} 
    List<ItemVM> Items {get;set;} 
} 

class Box { 
    int BoxId {get;set;} 
    List<Item> Items {get;set;} 
} 

隨着映射配置:

CreateMap<BoxVM, Box>(); 
CreateMap<ItemVM, Item>().ConvertUsing<ItemTypeConverter>(); 

當轉換BoxVMItems,所述ItemTypeConverter不被調用。在Box中留下一個空的Items集合。

BoxId映射正確。

我錯過了一個步驟嗎?

回答

0

看起來像它的工作。

using System.Collections.Generic; 

using AutoMapper; 

    [TestClass] 
    public class UnitTest1 
    { 
     [TestMethod] 
     public void TestMethod1() 
     { 

      Mapper.Initialize(cfg => 
       { 
        cfg.CreateMap<BoxVM, Box>(); 
        cfg.CreateMap<ItemVM, Item>().ConvertUsing<ItemTypeConverter>(); 

       }); 
      Mapper.AssertConfigurationIsValid(); 

      var boxVm = new BoxVM() 
      { 
       Value1 = "5", 
       Items = new List<ItemVM> { new ItemVM { Name = "Item1" } } 
      }; 

      var result = Mapper.Map<BoxVM, Box>(boxVm); 

      Assert.AreEqual(1, result.Items.Count); 
     } 
    } 

    public class Box 
    { 
     public string Value1 { get; set; } 
     public List<Item> Items { get; set; } 
    } 

    public class Item 
    { 
     public string Name { get; set; } 
    } 

    public class BoxVM 
    { 
     public string Value1 { get; set; } 
     public List<ItemVM> Items { get; set; } 
    } 

    public class ItemVM 
    { 
     public string Name { get; set; } 
    } 

    public class ItemTypeConverter : ITypeConverter<ItemVM, Item> 
    { 
     public Item Convert(ItemVM source, Item destination, ResolutionContext context) 
     { 
      return new Item { Name = source.Name }; 
     } 
    } 
+0

原因是屬性名稱中的拼寫錯誤! – PenFold

相關問題