Automapper - 如何使用automapper将三个实体映射到一个实体?

时间:2012-11-23 05:07:36

标签: c# automapper typeconverter

我有3个实体:Obj1Obj2Obj3

如何使用automapper将3实体映射到一个实体?

2 个答案:

答案 0 :(得分:7)

This post描述了如何使用以下助手类将多个对象映射到单个新对象中:

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

简单用法:

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

答案 1 :(得分:0)

我们假设需要将它们映射到Obj0。基本上你需要逐个映射它们。

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

在更高级的方案中,您可以将类型组合成一些CompositeObj并在Obj0CompositeObj之间创建映射。