none
IQueryable<T> and IOrderedQueryable<T> - Odd errors when constructing queries RRS feed

  • Question

  • I'm trying to dynamically build a query and it's gotten so screwy I'm considering dumping the whole deal and just creating a SQL query. Here's the deal.

    I need to filter on an object property - no problem.

    I also need to filter on whether or not the OrderBy property is null or has no entry, and the property in question isn't known until runtime. This is a problem, but I've asked about that in another post. As a short summary, I can't use something like this: .Where(column + " == null") for two reasons. The first is that the extension methods to implement IOrderedQueryable don't really like it when the " == null" is passed in. They use Reflection to get some of the magic done, and the column name returns null for GetProperty if you screw up the property name. The second reason is that I need the nulls/empty string entries to be included, just not at the top of the list. Jeez! Getting nulls to appear last seems to be akin to pulling teeth with pliers. Not that I've done that.

    I need to be able to construct the OrderBy clause at runtime. No problem (mostly). I use the dynamic linq class Scott Gu created, and all is good, except that it's not. If I pull the OrderBy clause out of the initial query code and put it in a conditional statement, I get the error that I can't convert an IQueryable collection to IOrderedQueryable. This is the difference:

     

    // This works, but has the nulls first problem.
    
    IOrderedQueryable<Project> unfilteredProjects = null
    ;

    if (sortType == "Asc" )
    {
    // Get the list of projects and run it through the ordered fields helper. unfilteredProjects = projectService.GetAllProjects() .Where(p => p.Status == status) .OrderBy(orderBy) .ThenBy(p => p.Name); } else { unfilteredProjects = projectService.GetAllProjects() .Where(p => p.Status == status) .OrderByDescending(orderBy) .ThenBy(p => p.Name); } // Change to creating the OrderBy in a different place, and // there be naught but errors. Says that IQueryable can't be
    // implicitly converted to
    IOrderedQueryable? .unfilteredProjects = projectService.GetAllProjects() .Where(p => p.Status == status); if (sortType == "Asc" )
    {
    unfilteredProjects = unfilteredProjects
    .OrderBy(orderBy)
    .ThenBy(p => p.Name);
    }

     

    I have a similar problem if I try to construct the Where clause somewhere else. In order to get the filtering I want, it seems I'll have to build the query in a conditional statement, setting the Where to look for nulls or empty strings. I'd rather not have to copy and paste the entire query for every condition, but when I try to construct it piece by piece, I'm getting these weird errors.

    Can anyone help?

    Thursday, March 3, 2011 6:26 PM

Answers