views:

18

answers:

2

Here is my method:

    public static MethodCallExpression ClonePropertyAssignmentLambda<T>(Expression source, string property)
    {
        var targetExp = Expression.Parameter(typeof (T), "target");
        var propertyInfo = typeof (T).GetProperty(property);
        var targetProperty = Expression.Property(targetExp, propertyInfo);
        var sourceProperty = Expression.Property(source, propertyInfo);

        return Expression.Call(targetProperty, ((PropertyInfo) targetProperty.Member).GetSetMethod(), sourceProperty);
    }

Here is how I'm calling it:

ClonePropertyAssignmentLambda<Person>(source, "Name")

I'm getting the error on the Expression.Call line. I get a similar error if I call GetGetMethod.

+3  A: 

You're trying to get the Name property of a string object.

Change it to

return Expression.Call(targetExp, propertyInfo.GetSetMethod(), sourceProperty);
SLaks
Thanks, you got it.
chief7
A: 

Never mind, I figured it out like 2 seconds after posting. Why do I always do that?

The first param for Expression.Call should be targetExp.

chief7
Because when you explain things to others, they become clear to you :-) If you didn't write the post, you might have spent much more time figuring things out.
Alexandra Rusina