简体   繁体   English

动态LINQ Where子句使用NaturalComparer作为字符串

[英]Dynamic LINQ Where Clause as string using NaturalComparer

I asked a question at Use a NaturalSortComparer in a LINQ Where Clause and now I have a more complex version. 在LINQ Where子句中的Use NaturalSortComparer中提出了一个问题,现在我有了一个更复杂的版本。

That query assumed a simple query like ProductCode > 'U5' and using a NaturalComparer in the Where clause: 该查询假定使用ProductCode>'U5'这样的简单查询,并在Where子句中使用NaturalComparer:

    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. 下面的代码是一个简单的已知示例,但实际上,该过滤器是嵌套的,具有And / OR操作数的组合,并且直到运行时才知道。 I want to pass into a dynamic LINQ query as a string: The data is on SQL Server db using LINQ to Entities. 我想以字符串形式传递给动态LINQ查询:数据在SQL Server db上使用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? 我将如何使用NaturalComparer处理字符串字段以及要正常处理的任何其他字段类型?

You are going to be able to translate your custom string comparison function into SQL. 您将能够将自定义字符串比较功能转换为SQL。 EF is just going to crash at runtime if you try. 如果尝试,EF只会在运行时崩溃。 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. 这意味着您唯一的真实选择是下拉整个数据集并在内存中完成整个操作。

Dynamic Linq is just plain evil, and should be avoided. 动态Linq只是简单的邪恶,应该避免。

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. 您真正想在这里使用的是Joe Albahari的Predicate Builder ,它使您可以动态构建一个where子句(与Dynamic linq一样),但是要使用常规LINQ的类型安全属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM