用于RUntime列投影的动态LINQ

时间:2013-04-25 19:40:56

标签: c# linq

我试图为所选列实现动态LINQ查询以显示LINQ查询中的输出列。 这是错误:

  

/ Property'System.String CompanyCode'未定义类型   'System.String'“

public static void SelectProjection()
{
    DataMovementDataContext dbMovement = new DataMovementDataContext();
    var entity = dbMovement.ListofAccountingDocs2_1075s.AsQueryable();
    Type type = entity.ElementType;
    var entityParam = Expression.Parameter(entity.ElementType, "row");
    Expression expr = entityParam;
    string[] props = "AccountingDocumentNbr,CompanyCode,FiscalYearNbr".Split(',');
    foreach (string prop in props)
    {
        // use reflection (not ComponentModel) to mirror LINQ
        PropertyInfo pi = type.GetProperty(prop);
        expr = Expression.Property(expr, pi);
        type = pi.PropertyType;  
    }
    // row => row.Property
    // var columnLambda = Expression.Lambda(  Expression.Property(entityParam, "GLCompanyCode"), entityParam);
    var columnLambda = Expression.Lambda(Expression.Property(expr, "AccountingDocumentNbr,GLCompanyCode"), entityParam);

    // Items.Select(row => row.Property)
    var selectCall = Expression.Call(typeof(Queryable), "Select", new Type[] { entity.ElementType, columnLambda.Body.Type }, entity.Expression, columnLambda);

    // Items.Select(row => row.Property).Distinct
    var distinctCall = Expression.Call(typeof(Queryable), "Distinct", new Type[] { typeof(string) }, selectCall);


    // colvalue => colvalue
    var sortParam = Expression.Parameter(typeof(string), "AccountingDocumentNbr");
    var columnResultLambda = Expression.Lambda(sortParam, sortParam);

    // Items.Select(row => row.Property).Distinct.OrderBy(colvalue => colvalue)
    var ordercall = Expression.Call(typeof(Queryable), "OrderBy",
                    new Type[] { typeof(string), columnResultLambda.Body.Type },
                    distinctCall, columnResultLambda);

    var result =  entity.Provider.CreateQuery(ordercall);
    foreach (var item in result)
    {
        Console.Write(item);
    }
}

任何人都可以帮我解决上述错误吗?

1 个答案:

答案 0 :(得分:-1)

如果我们看一下这段代码:

   // I chnaged this part:

   string[] props = new string[]
   {
        "AccountingDocumentNbr",
        "CompanyCode",
        "FiscalYearNbr"
   };


    Expression expr;
    Type type = entity.ElementType;

    foreach (string prop in props)
    {
        PropertyInfo pi = type.GetProperty(prop);

        expr = Expression.Property(expr, pi);

        type = pi.PropertyType;   // This line may cause your loop 
                                  // to do something you dont want to do?
    }

在我看来,你的循环沿着属性,获取一个字符串,然后搜索一个名为CompanyCode的prop,类String显然没有。

您的循环目前执行以下操作:

从类型

获取名为AccountingDocumentNbr

的属性

从属性AccountingDocumentNbr的返回类型获取名为CompanyCode

的属性

形成返回类型的属性CompanyCode获取名为FiscalYearNbr的属性的类型

我几乎不怀疑这是你真正想做的事情。