I need to copy properties of one object to another, both objects can be of different type, can have properties of same name. These property can also be of complex type.
You can try using the AutoMapper as @Kevin mentioned. If you still need a custom method, you can try this. Note: It copies the value to the property in the target object itself and does not look for the property as in the expression tree.
private static void Assign<T1, T2>(T1 T1Obj, T2 T2Obj, Expression<Func<T1, object>> memberLamda)
{
var memberSelectorExpression = memberLamda.Body as MemberExpression;
if (memberSelectorExpression != null)
{
var sourceProperty = memberSelectorExpression.Member as PropertyInfo;
if (sourceProperty != null)
{
var targetProperty = T2Obj.GetType().GetProperty(sourceProperty.Name);
if (targetProperty != null)
{
targetProperty.SetValue(T2Obj, GetValue(T1Obj, memberSelectorExpression));
}
}
}
}
public static object GetValue<T>(T source, MemberExpression expr)
{
var sourceProperty = expr.Member as PropertyInfo;
var nextExpression = expr.Expression as MemberExpression;
if (nextExpression == null)
{
return sourceProperty.GetValue(source);
}
var sourcePart = GetValue(source, nextExpression);
return sourceProperty.GetValue(sourcePart);
}
Use AutoMapper and ignore the members you don't want to map.
config.CreateMap<Person, Employee>()
.ForMember(d => d.Name, o => o.MapFrom(s => s.FullName))
.ForMember(d => d.Age, o => o.Ignore());