2014-10-16 137 views
1

我想将一个简单的KeyValuePair对象集合映射到我的自定义类。 可惜的是我只得到一个异常AutoMapper - 映射不起作用

Missing type map configuration or unsupported mapping. 

Mapping types: 
RuntimeType -> DictionaryType 
System.RuntimeType -> AutoMapperTest.Program+DictionaryType 

Destination path: 
IEnumerable`1[0].Type.Type 

Source value: 
System.Collections.Generic.KeyValuePair`2[AutoMapperTest.Program+DictionaryType,System.String] 

码在最简单的形式重现此问题

class Program 
{ 
    public enum DictionaryType 
    { 
     Type1, 
     Type2 
    } 

    public class DictionariesListViewModels : BaseViewModel 
    { 
     public string Name { set; get; } 
     public DictionaryType Type { set; get; } 
    } 

    public class BaseViewModel 
    { 
     public int Id { set; get; } 
    } 

    static void Main(string[] args) 
    { 
     AutoMapper.Mapper.CreateMap< 
      KeyValuePair<DictionaryType, string>, DictionariesListViewModels>() 
      .ConstructUsing(r => 
      { 
       var keyValuePair = (KeyValuePair<DictionaryType, string>)r.SourceValue; 
       return new DictionariesListViewModels 
       { 
        Type = keyValuePair.Key, 
        Name = keyValuePair.Value 
       }; 
      }); 

     List<KeyValuePair<DictionaryType, string>> collection = 
      new List<KeyValuePair<DictionaryType, string>> 
     { 
      new KeyValuePair<DictionaryType, string>(DictionaryType.Type1, "Position1"), 
      new KeyValuePair<DictionaryType, string>(DictionaryType.Type2, "Position2") 
     }; 

     var mappedCollection = AutoMapper.Mapper.Map<IEnumerable<DictionariesListViewModels>>(collection); 


     Console.ReadLine(); 
    } 
} 

我有其他的映射创建以同样的方式(不枚举)和他们的作品,所以它必须是一个问题,但如何解决它呢?这一定很简单,我有问题需要注意。

回答

4

ConstructUsing仅指示AutoMapper如何构造目标类型。在构造目标类型的实例之后,它将继续尝试映射每个属性。

你想,而不是什么是ConvertUsing告诉AutoMapper要接管整个转换过程:

Mapper.CreateMap<KeyValuePair<DictionaryType, string>, DictionariesListViewModels>() 
    .ConvertUsing(r => new DictionariesListViewModels { Type = r.Key, Name = r.Value }); 

例子:https://dotnetfiddle.net/Gxhw6A