1

I asked a question at Use a NaturalSortComparer in a LINQ Where Clause and now I have a more complex version.

That query assumed a simple query like ProductCode > 'U5' and using a NaturalComparer in the Where clause:

    var comparer = new NaturalComparer();
Table1.AsEnumerable().Where(t=> 
    comparer.Compare(t.ProductString, "U5") >= 0);

The code below for a simple known example, but in reality the filter is nested and has combinations of And/OR operands and is unknown until runtime. I want to pass into a dynamic LINQ query as a string: The data is on SQL Server db using LINQ to Entities.

Example:

    var queryString= "((ProductCode > 'U5' Or TagString LIKE '%k') and Date < Now) 
Or (MessageString = 'text' And Date < yesterday) OR SomeOtherString = '100' 
or PriorityString <= '100X' or SomeInt =15";

    // Call the constructor with the specified query and the ObjectContext.
    ObjectQuery<Product> productQuery =
        new ObjectQuery<Product>(queryString, context);

How would I process the string fields using the NaturalComparer, and any other field type to be processed as normal?

Andrew Roberts
  • 990
  • 2
  • 12
  • 26
  • For what it's worth, I gave an answer to your former question (after another answer was accepted) that actually does offer a the more generalized solution that you're looking for without resorting to Dynamic LINQ, or pulling the entire table into EF for querying: http://stackoverflow.com/a/25800360/956150 – jdmcnair Sep 17 '14 at 14:15

2 Answers2

1

You are going to be able to translate your custom string comparison function into SQL. EF is just going to crash at runtime if you try. Your expressions also are interwoven with these custom string comparisons in ways that would prevent you from doing all of those operations on the database, only doing the string comparisons on the already filtered results. This means that your only real choice is to pull down the entire data set and do the whole thing in memory.

Servy
  • 202,030
  • 26
  • 332
  • 449
-1

Dynamic Linq is just plain evil, and should be avoided.

What you really want to use here is Joe Albahari's Predicate Builder, which let's you build a where clause on the fly (as with Dynamic linq), but by using the type-safe properties of regular LINQ.

James Curran
  • 101,701
  • 37
  • 181
  • 258
  • Hi James, The reason I'm wanting to pass a string in is that I am using a Dev Express FilterControl (https://documentation.devexpress.com/#windowsforms/clsDevExpressXtraEditorsFilterControltopic). This control gives me the where clause as a string. – Andrew Roberts Sep 14 '14 at 23:51