Created
December 30, 2018 18:25
-
-
Save StefH/acb14563c5d2bfceb7500083b779e0d8 to your computer and use it in GitHub Desktop.
AutoMapper Extensions : Unflatten
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
using System.Reflection; | |
using JetBrains.Annotations; | |
// ReSharper disable once CheckNamespace | |
namespace AutoMapper | |
{ | |
public static class AutoMapperExtensions | |
{ | |
[PublicAPI] | |
public static void Unflatten<TSource, TDestination, TMember>(this IMemberConfigurationExpression<TSource, TDestination, TMember> config) | |
{ | |
config.MapFrom((source, destination, member, resolutionContext) => | |
{ | |
string prefix = typeof(TMember).Name; | |
TMember resolvedObject = (TMember) Activator.CreateInstance(typeof(TMember)); | |
PropertyInfo[] targetProperties = resolvedObject.GetType().GetProperties(); | |
foreach (var sourceMember in source.GetType().GetProperties()) | |
{ | |
// find the matching target property and populate it | |
PropertyInfo matchedProperty = targetProperties.FirstOrDefault(p => sourceMember.Name == prefix + p.Name); | |
matchedProperty?.SetValue(resolvedObject, sourceMember.GetValue(source)); | |
} | |
return resolvedObject; | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment