简体   繁体   中英

AutoMapper - complex mapping involving function call

I'm just getting to grips with AutoMapper and love how it works. However I believe it can map some complex scenarios that I'm currently wiring up manually. Does anyone have any suggestions / tips to remove my manual processes from the below simplified example and accelerate my learning curve?

I have a source object like so:

public class Source
{
    public Dictionary<string, object> Attributes;
    public ComplexObject ObjectWeWantAsJson;
}

and a destination object like so:

public class Destination
{
    public string Property1; // Matches with Source.Attributes key
    public string Property2; // Matches with Source.Attributes key
    // etc.
    public string Json;
}

My configuration for AutoMapper is minimal:

var config = new MapperConfiguration(cfg => {});
var mapper = config.CreateMapper();

And my conversion code is like so:

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

Any pointers or suggestions are most appreciated. Thanks in advance!

you might be interested in writing the conversion code using a 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM