Skip to main content
 首页 » 编程设计

c#之AutoMapper之映射不起作用

2024年02月06日26zdz8207

我想将一个简单的 KeyValuePair 对象集合映射到我的自定义类。 不幸的是我只得到一个异常(exception)

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

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

请您参考如下方法:

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

您想要的是 ConvertUsing,它告诉 AutoMapper 您想要接管整个转换过程:

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

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