自动映射器 - 涉及函数调用的复杂映射



我刚刚掌握了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;
}

我对自动映射器的配置是最小的:

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

任何指示或建议将不胜感激。提前感谢!

您可能

有兴趣使用 TypeConverter 编写转换代码。

internal class CustomConverter : TypeConverter<List<Source>, List<Destination>>
{
    protected override List<Destination> ConvertCore(List<Source> source)
    {
        if (source == null) return null;
        if (!source.Any()) return null;
        var output = new List<Destination>();
        output.AddRange(source.Select(a => new Destination
        {
            Property1 = (string)a.Attributes["Property1"],
            Property2 = (string)a.Attributes["Property2"],
            Json = JsonConvert.SerializeObject(a.ObjectWeWantAsJson)
        }));
        return output;
    }
}
var source = new List<Source>
        {
            new Source{
                Attributes = new Dictionary<string,object>{
                    {"Property1","Property1-Value"},
                    {"Property2","Property2-Value"}
                },
                ObjectWeWantAsJson = new ComplexObject{Name = "Test", Age = 27}
            }
        };
Mapper.CreateMap<List<Source>, List<Destination>>().
            ConvertUsing(new CustomConverter());
var dest = Mapper.Map<List<Destination>>(source);

最新更新