AutoMapper-映射没有';不起作用
本文关键字:不起作用 映射 AutoMapper- | 更新日期: 2023-09-27 18:26:49
我想将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();
}
}
我用同样的方式创建了其他映射(没有枚举),它们也能工作,所以这肯定是个问题,但如何解决它?这一定是一些简单的事情,我有问题要注意。
ConstructUsing
仅指示AutoMapper如何构造目标类型。在构造目标类型的实例后,它将继续尝试映射每个属性。
你想要的是ConvertUsing
,它告诉AutoMapper你想接管整个转换过程:
Mapper.CreateMap<KeyValuePair<DictionaryType, string>, DictionariesListViewModels>()
.ConvertUsing(r => new DictionariesListViewModels { Type = r.Key, Name = r.Value });
示例:https://dotnetfiddle.net/Gxhw6A