我刚刚开始掌握 AutoMapper 并喜欢它的工作原理。但是我相信它可以映射一些我目前手动连接的复杂场景。有没有人有任何建议/提示可以从下面的简化示例中删除我的手动过程并加快我的学习曲线?
我有一个像这样的源对象:
public class Source
{
public Dictionary<string, object> Attributes;
public ComplexObject ObjectWeWantAsJson;
}
和这样的目标对象:
public class Destination
{
public string Property1; // Matches with Source.Attributes key
public string Property2; // Matches with Source.Attributes key
// etc.
public string Json;
}
我对 AutoMapper 的配置是最小的:
var config = new MapperConfiguration(cfg => {});
var mapper = config.CreateMapper();
我的转换代码是这样的:
var destinationList = new List<Destination>();
foreach (var source in sourceList)
{
var dest = mapper.Map<Dictionary<string, object>, Destination(source.Attributes);
// I'm pretty sure I should be able to combine this with the mapping
// done in line above
dest.Json = JsonConvert.SerializeObject(source.ObjectWeWantAsJson);
// I also get the impression I should be able to map a whole collection
// rather than iterating through each item myself
destinationList.Add(dest);
}
非常感谢任何指针或建议。提前致谢!