Stefan
Stefan

Reputation: 187

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

I can't seem to create an equivalent query in reflection, of a LINQ query.

The goal is to run a query on an Entity Framework DBContext, but specifying the Tablename, and the where clause. There are several tables, so I do not want to copy/paste the same LINQ, for different tables.

The code below works with LINQ, but the reflections equivalent (although I cast it to System.Linq.IQueryable), does not allow me to add a .where clause.

I included using System.Linq; in the class.

Examples I researched from stackoverflow, exposes the Where() clause.

It's probably something minor I am overlooking. (missing a reference?)

        // 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);

Upvotes: 1

Views: 809

Answers (1)

Amy B
Amy B

Reputation: 110171

You need to cast to IQueryable<HEADCOUNT_NEW>

Where is an extension method which works on IQueryable<T>, not IQueryable.

Upvotes: 1

Related Questions