0

我试图为选定的列实现动态 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);
    }
}

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

4

1 回答 1

-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 的道具,String 类显然没有。

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

从类型获取名为 AccountingDocumentNbr 的属性

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

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

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

于 2013-04-25T20:12:23.193 回答