AutoMapper - 涉及函数调用的复杂映射

时间:2016-06-08 10:35:10

标签: c# automapper automapper-4

我正忙着掌握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);
}

非常感谢任何指针或建议。提前谢谢!

1 个答案:

答案 0 :(得分:0)

您可能有兴趣使用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);