0

我刚刚开始掌握 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);
}

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

4

1 回答 1

1

您可能有兴趣使用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);
于 2016-06-08T11:31:43.073 回答