matthewwren 0 Newbie Poster

I am trying to create an expression for each property based on an existing expression, but I am getting a bit stuck. Here is a code sample to illustrate the problem. The expression gets built correctly but when I try to compile it throws an InvalidOperationException with the message 'Lambda Parameter not in scope'.

using System;
using System.Linq.Expressions;

namespace ExpressionTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Expression<Func<ContactModel, ContactAddressModel>> expression = m => m.Address;
            EditorForExt(expression);
        }

        public static string EditorForExt<TModel, TValue>(
            Expression<Func<TModel, TValue>> expression)
            where TModel : class
        {
            foreach (var propertyInfo in typeof(TValue).GetProperties())
            {
                var parameterExpression = Expression.Parameter(typeof(TModel), expression.Parameters[0].Name);
                var memberExpression = Expression.Property(expression.Body, propertyInfo);
                var unaryExpression = Expression.TypeAs(memberExpression, typeof(object));

                Expression<Func<TModel, object>> newExpression =
                    Expression.Lambda<Func<TModel, object>>(unaryExpression, new[] { parameterExpression });

                //Following line throws InvalidOperationException 
                //'Lambda Parameter not in scope'
                var compiledExpression = newExpression.Compile();
            }

            return string.Empty;
        }
    }

    public class ContactModel
    {
        public ContactModel()
        {
            Address = new ContactAddressModel();
        }
        public int Age { get; set; }
        public ContactAddressModel Address { get; set; }
    }

    public class ContactAddressModel
    {
        public string Line1 { get; set; }
        public string Line2 { get; set; }
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.