简体   繁体   中英

Automapper - How to map three entity to one with automapper?

I have 3 entity: Obj1 , Obj2 , Obj3

How to map 3 entity to one with automapper?

This post describes how to map multiple objects into a single new object, using the following helper class:

public static class EntityMapper
{
    public static T Map<T>(params object[] sources) where T : class
    {
        if (!sources.Any())
        {
            return default(T);
        }

        var initialSource = sources[0];

        var mappingResult = Map<T>(initialSource);

        // Now map the remaining source objects
        if (sources.Count() > 1)
        {
            Map(mappingResult, sources.Skip(1).ToArray());
        }

        return mappingResult;
    }

    private static void Map(object destination, params object[] sources)
    {
        if (!sources.Any())
        {
            return;
        }

        var destinationType = destination.GetType();

        foreach (var source in sources)
        {
            var sourceType = source.GetType();

            Mapper.Map(source, destination, sourceType, destinationType);
        }
    }

    private static T Map<T>(object source) where T : class
    {
        var destinationType = typeof(T)
        var sourceType = source.GetType();

        var mappingResult = Mapper.Map(source, sourceType, destinationType);

        return mappingResult as T;
    }
}  

Simple usage:

var personViewModel = EntityMapper.Map<PersonViewModel>(person, address, comment);

Let's suppose that it is needed to map them to Obj0 . Basically you need to map them one by one.

Mapper.Map(Obj1, Obj0);
Mapper.Map(Obj2, Obj0);
Mapper.Map(Obj3, Obj0);

In more advanced scenarios you can compose you types into some CompositeObj and create mapping between Obj0 and CompositeObj .

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