如何动态创建Lambda表达式

时间:2011-09-02 03:09:42

标签: c# entity-framework lambda

如何动态创建表达式树,看起来像......

    p => new { p.FAMILY, p.CACHE_FAMILY, p.CUSTOMER_CODE, p.CCC, p.OPERATION, p.EVAL_CODE, p.VDT_FLAG, p.TEST_PLATFORM, p.PCBA_VENDOR }

目前我的代码只能处理单个表达式。

public static void MapKeys<TEntity>(EntityTypeConfiguration<TEntity> mapper, string tableName)
        where TEntity : class
    {
        Type type = typeof(TEntity);
        ParameterExpression arg = Expression.Parameter(type, "x");
        Expression expr = arg;


        string propertyName = string.Empty;
        List<string> indexKeys = GetIndexKeyList(tableName);

        foreach (string key in indexKeys)
        {
            PropertyInfo pi = type.GetProperty(key,
            BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
            expr = Expression.Property(expr, pi);


            LambdaExpression lambda = Expression.Lambda(expr, arg);

            Expression<Func<TEntity, string>> expression = (Expression<Func<TEntity, string>>)lambda;
            mapper.HasKey(expression);
        }
    }

0 个答案:

没有答案