Last active
July 7, 2016 23:09
-
-
Save mbenford/e507989a79925896abdcf64563fe2c57 to your computer and use it in GitHub Desktop.
Port of http://martinburrows.net/blog/2016/01/18/automatic-unflattening-with-automapper/ that works with AutoMapper 3.x and C# 5
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
public static class MappingExtensions | |
{ | |
public static void Unflatten<T>(this IMemberConfigurationExpression<T> config) | |
{ | |
config.ResolveUsing(resolutionResult => | |
{ | |
var context = resolutionResult.Context; | |
var prefix = context.MemberName; | |
var destProperties = context.DestinationType.GetProperties(); | |
var dest = Activator.CreateInstance(context.DestinationType); | |
foreach (var sourceMember in context.SourceType.GetProperties()) | |
{ | |
var matchedProperty = destProperties.FirstOrDefault(p => sourceMember.Name == prefix + p.Name); | |
if (matchedProperty != null) matchedProperty.SetValue(dest, sourceMember.GetValue(context.SourceValue)); | |
} | |
return dest; | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment