Merge two objects to produce third using AutoMapper

前端 未结 5 1539
日久生厌
日久生厌 2020-12-14 01:25

I know it\'s AutoMapper and not AutoMerge(r), but...

I\'ve started using AutoMapper and have a need to Map A -> B, and to add some properties from C so that B become

5条回答
  •  遥遥无期
    2020-12-14 02:06

    I searched hard and long on this question and ended up implementing an extension method that merge's objects together.

    I reference the steps on my blog http://twistyvortek.blogspot.com and here's the code:

    
        using System;
    
        namespace Domain.Models
        {
            public static class ExtendedMethods
            {
                /// 
                /// 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
                /// 
                /// Type Parameter of the merging objects. Both objects must be of the same type.
                /// The object that is receiving merge data (modified)
                /// The object supplying the merging properties.  (unmodified)
                /// The primary object (modified)
                public static T MergeWith(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;
                }
            }
        }
    
    

    Usage includes method chaining so you can merge multiple objects into one.

    What I would do is use automapper to map part of the properties from your various sources into the same class of DTOs, etc. and then use this extension method to merge them together.

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

    Hope this helps someone.

提交回复
热议问题