Я долго и усердно искал этот вопрос и в итоге реализовал метод расширения, который объединяет объекты.
Я ссылаюсь на шаги в моем блоге 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);
Надеюсь, это кому-нибудь поможет.