使用AutoMapper合并两个对象以生成第三个对象

Jas*_*and 26 automapper

我知道它是AutoMapper而不是AutoMerge(r),但......

我已经开始使用AutoMapper并且需要映射A - > B,并从C添加一些属性,以便B成为A + C的一种平面组合.

这是否可以在AutoMapper中使用AutoMapper来进行繁重的工作然后手动映射其他属性?

epi*_*tka 14

这不行吗?

var mappedB = _mapper.Map<A,B>(aInstance);
_mapper.Map(instanceC,mappedB);
Run Code Online (Sandbox Code Playgroud)

  • 我不知道 - 是吗? (26认同)

Omu*_*Omu 13

您可以使用ValueInjecter执行此操作

 a.InjectFrom(b)
  .InjectFrom(c)
  .InjectFrom<SomeOtherMappingAlgorithmDefinedByYou>(dOrBOrWhateverObject);
Run Code Online (Sandbox Code Playgroud)

  • @Omu,非常有趣的工具,购买我不确定,如果您回答了上面的问题。 (2认同)

sar*_*ret 5

据我记得,使用AutoMapper时,您必须将映射定义为从一个输入到一个输出(也许自那以来已经改变了-一个月没有使用它了)。

如果是这种情况,则您的映射可能应该是KeyValuePair<A,C>(或包含A和C的某种对象)=> B

这样,您可以将一个已定义的输入参数映射到您的输出对象


The*_*het 5

我在这个问题上进行了长时间的搜索并最终实现了将对象合并在一起的扩展方法.

我参考了我的博客http://twistyvortek.blogspot.com上的步骤 ,这里是代码:


    using System;

    namespace Domain.Models
    {
        public static class ExtendedMethods
        {
            /// <summary>
            /// Merges two object instances together.  The primary instance will retain all non-Null values, and the second will merge all properties that map to null properties the primary
            /// </summary>
            /// <typeparam name="T">Type Parameter of the merging objects. Both objects must be of the same type.</typeparam>
            /// <param name="primary">The object that is receiving merge data (modified)</param>
            /// <param name="secondary">The object supplying the merging properties.  (unmodified)</param>
            /// <returns>The primary object (modified)</returns>
            public static T MergeWith<T>(this T primary, T secondary)
            {
                foreach (var pi in typeof (T).GetProperties())
                {
                    var priValue = pi.GetGetMethod().Invoke(primary, null);
                    var secValue = pi.GetGetMethod().Invoke(secondary, null);
                    if (priValue == null || (pi.PropertyType.IsValueType && priValue == Activator.CreateInstance(pi.PropertyType)))
                    {
                        pi.GetSetMethod().Invoke(primary, new[] {secValue});
                    }
                }
                return primary;
            }
        }
    }

用法包括方法链接,因此您可以将多个对象合并为一个.

我要做的是使用automapper将各种来源的部分属性映射到同一类DTO等,然后使用此扩展方法将它们合并在一起.


    var Obj1 = Mapper.Map(Instance1);
    var Obj2 = Mapper.Map(Instance2);
    var Obj3 = Mapper.Map(Instance3);
    var Obj4 = Mapper.Map(Instance4);

    var finalMerge = Obj1.MergeWith(Obj2)
                              .MergeWith(Obj3)
                              .MergeWith(Obj4);

希望这有助于某人.

  • public static T MergeWith <T>(这个T primary,T secondary) (3认同)