lundi 24 septembre 2018

How to get a property from an anonymous type using Expression.Parameter?

I'm trying to generate a dynamic lambda using a anonymous class, however I've an issue when I try to get the property related with my model in the anonymous class.

public class Program
{
    public class Model
    {
        public string Folder { get; set; }
    }

    public static void Main()
    {
        Select<Model>(new string[] { "Folder" });
    }

    public static void Select<TResult>(string[] propertyNames)
    {
        var anonymousType = CreateAnonymousType(propertyNames);
        var parameter = Expression.Parameter(anonymousType.GetType(), "item");

        foreach (var prop in parameter.GetType().GetProperties())
            Console.WriteLine(prop);

        var bindings = propertyNames
            .Select(name => name.Trim())
            .Select(name => Expression.Bind(
                typeof(TResult).GetProperty(name),
                Expression.Property(parameter, name) // here I have the issue, when the method try to find the property "Folder" in the anonymou type, throw an exception.
            ));

        var newT = Expression.MemberInit(Expression.New(typeof(TResult)), bindings);
        var lambda = Expression.Lambda<Func<Type, TResult>>(newT, parameter);

        Console.WriteLine(lambda.ToString());
    }

    public static Type CreateAnonymousType(string[] properties)
    {
        AssemblyName dynamicAssemblyName = new AssemblyName("TempAssembly");
        AssemblyBuilder dynamicAssembly = AssemblyBuilder.DefineDynamicAssembly(dynamicAssemblyName, AssemblyBuilderAccess.Run);
        ModuleBuilder dynamicModule = dynamicAssembly.DefineDynamicModule("TempAssembly");

        TypeBuilder dynamicAnonymousType = dynamicModule.DefineType("AnonymousType", TypeAttributes.Public);

        foreach (var property in properties)
            dynamicAnonymousType.DefineField(property, typeof(object), FieldAttributes.Public);

        return dynamicAnonymousType.CreateType();
    }
}

When I execute the code: Expression.Property(parameter, name) throw this exception:

Run-time exception (line 23): Instance property 'Folder' is not defined for type 'System.RuntimeType'

How can I resolve this issue?





Aucun commentaire:

Enregistrer un commentaire