动态LINQ运行时列投影

本文关键字:投影 运行时 LINQ 动态 | 更新日期: 2023-09-27 18:11:00

我试图实现动态LINQ查询所选列显示有输出列在LINQ查询。下面是错误:

/属性的系统。String CompanyCode'没有为type定义的系统。字符串"

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);
    }
}
有谁能帮我解决上面的错误吗?

动态LINQ运行时列投影

看下面的代码:

   // 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的道具,这类字符串显然没有

你的循环现在做以下事情:

从type获取名为AccountingDocumentNbr的属性

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

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

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