AutoMapper - 映射不起作用

时间:2014-10-16 11:55:35

标签: c# automapper

我想将一个简单的KeyValuePair对象集合映射到我的自定义类。 不幸的是,我只得到一个例外

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

我有其他映射以相同的方式创建(没有枚举)并且它们有效,所以它一定是个问题,但是如何解决它?它必须是简单的,我有问题需要注意。

1 个答案:

答案 0 :(得分: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

相关问题