使用反射在 DbContext 上编写等效的 LINQ 查询缺少 where 条件

Writing an equivalent LINQ query , on a DbContext, using Reflection, is missing a where condition

我似乎无法创建 LINQ 查询的等效查询。

目标是 运行 查询 Entity Framework DBContext,但指定表名和 where 子句。有几个表,所以我不想 copy/paste 相同的 LINQ,用于不同的表。

下面的代码适用于 LINQ,但等效的反射(尽管我将其转换为 System.Linq.IQueryable)不允许我添加 .where 子句。

我在 class 中包含了 using System.Linq;

我从 Whosebug 研究的示例公开了 Where() 子句。

这可能是我忽略的一些小问题。 (缺少参考?)

        // Link to TREESTRUCTURES Database
        var DaContext = new WebApplication7.Models.Db_Entities.TREE_STRUCTURESEntities();
        DaContext.Database.CommandTimeout=300;

        // This works 100% for "HEADCOUNT_NEW"
        var daTreeLeaves = DaContext.HEADCOUNT_NEW
            .Where(x => x.PARENT_COMPONENT == "" && x.COMPONENT_DESCRIPTION == "Headcounts")
            .Select(x => new { x.COMPONENT, x.COMPONENT_DESCRIPTION })
            .OrderBy(x => x.COMPONENT)
            .ToList();

        // Reflections! = This works - Selecting from "HEADCOUNT_NEW" or any other specified available table;
        PropertyInfo dbsetinfo = DaContext.GetType().GetProperties().FirstOrDefault(p => p.Name.ToUpper().Equals("HEADCOUNT_NEW"));

        // I can't seem to get the `.Where()` clause right here (although this code  does return values :) )
        // I omitted the Where here as it would not compile.
        System.Linq.IQueryable anyDbSet = ((IQueryable)dbsetinfo.GetValue(DaContext));

        // Below is my attempt (pseudocode), but the error 
        // "IQueryable does not contain a definition for Where" is returned by VStudio
        System.Linq.IQueryable anyDbSet2 = ((IQueryable)dbsetinfo.GetValue(DaContext)).Where("Id=" + pseudocode);

您需要转换为 IQueryable<HEADCOUNT_NEW>

Where 是一种扩展方法,适用于 IQueryable<T>,不适用于 IQueryable