Skip to content

Instantly share code, notes, and snippets.

@lbargaoanu
Last active April 19, 2023 14:06
Show Gist options
  • Save lbargaoanu/8e15798a8b4facd292feb5fcfbf1e3f7 to your computer and use it in GitHub Desktop.
Save lbargaoanu/8e15798a8b4facd292feb5fcfbf1e3f7 to your computer and use it in GitHub Desktop.
using static Expression;
public static class Extensions
{
public static IMappingExpression<TSource, TDestination> Flatten<TSource, TDestination, TSourceMember>(
this IMappingExpression<TSource, TDestination> map,
Expression<Func<TSource, TSourceMember>> source)
{
var innerSourceProperties =
from sp in typeof(TSourceMember).GetProperties()
where sp.CanRead
join dp in typeof(TDestination).GetProperties()
on sp.Name equals dp.Name
where dp.CanWrite
select sp;
foreach(var innerSourceProperty in innerSourceProperties)
{
var innerProperty = Expression.Convert(Expression.Property(source.Body, innerSourceProperty), typeof(object));
var mapFrom = Expression.Lambda<Func<TSource, object>>(innerProperty, source.Parameters);
map.ForMember(innerSourceProperty.Name, c => c.MapFrom(mapFrom));
}
return map;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment