使用AutoMapper映射字典 [英] Mapping dictionaries with AutoMapper
问题描述
鉴于这些类,我该如何映射它们的字典?
Given this these classes, how can I map a dictionary of them?
public class TestClass
{
public string Name { get; set; }
}
public class TestClassDto
{
public string Name { get; set; }
}
Mapper.CreateMap<TestClass, TestClassDto>();
Mapper.CreateMap<Dictionary<string, TestClass>,
Dictionary<string, TestClassDto>>();
var testDict = new Dictionary<string, TestClass>();
var testValue = new TestClass() {Name = "value1"};
testDict.Add("key1", testValue);
var mappedValue = Mapper.Map<TestClass, TestClassDto>(testValue);
var mappedDict = Mapper.Map<Dictionary<string, TestClass>,
Dictionary<string, TestClassDto>>(testDict);
映射其中一个,在这种情况下,mappedValue可以正常工作.
Mapping one of them, mappedValue in this case, works fine.
映射它们的字典最终在目标对象中没有任何条目.
Mapping a dictionary of them ends up with no entries in the destination object.
我在做什么?
推荐答案
您遇到的问题是因为AutoMapper难以映射词典的内容.您必须考虑它的存储-在这种情况下为 KeyValuePairs .
The problem you are having is because AutoMapper is struggling to map the contents of the Dictionary. You have to think what it is a store of - in this case KeyValuePairs.
如果您尝试为KeyValuePair组合创建一个映射器,您会很快发现您不能直接创建,因为 Key属性没有设置器.
If you try create a mapper for the KeyValuePair combination you will quickly work out that you can't directly as the Key property doesn't have a setter.
AutoMapper通过允许您使用构造函数进行映射来解决此问题.
AutoMapper gets around this though by allowing you to Map using the constructor.
/* Create the map for the base object - be explicit for good readability */
Mapper.CreateMap<TestClass, TestClassDto>()
.ForMember( x => x.Name, o => o.MapFrom( y => y.Name ) );
/* Create the map using construct using rather than ForMember */
Mapper.CreateMap<KeyValuePair<string, TestClass>, KeyValuePair<string, TestClassDto>>()
.ConstructUsing( x => new KeyValuePair<string, TestClassDto>( x.Key,
x.Value.MapTo<TestClassDto>() ) );
var testDict = new Dictionary<string, TestClass>();
var testValue = new TestClass()
{
Name = "value1"
};
testDict.Add( "key1", testValue );
/* Mapped Dict will have your new KeyValuePair in there */
var mappedDict = Mapper.Map<Dictionary<string, TestClass>,
Dictionary<string, TestClassDto>>( testDict );
这篇关于使用AutoMapper映射字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!