Using a string where clause with PredicateBuilder in LinqPad for creating dynamic where clause

家住魔仙堡 提交于 2019-12-13 05:24:16

问题


I am trying to create a dynamic query in LinqPad with PredicateBuilder enabled.

I first create a string that corresponds to the where clause for a query like '(orderid >100 AND customerid<=100)' and then try to use this string in building a LINQ query with PredicateBuilder. The dynamic query is represented by the variable 'dynamicResult' in code give at end of this post. The query is on Orders table of Northwind database in SQL Server 2008 R2.

The query throws this error in LinqPad, when I try to execute it:

Cannot implicitly convert type 'string' to 'System.Linq.Expressions.Expression>'

Question: How can I use a filter that is a string like '(orderid >100 AND customerid<=100)' with PredicateBuilder ? I had 'C# Statements' selected from LinqPad when trying to execute the below code.

I am trying to dynamically build a where condition for a LINQ query.

int? orderParam = 100;
string orderOperator = ">=";
string linqFilter = "";
linqFilter= String.Format("{0} {1} {2}", "o.OrderID", orderOperator, orderParam);
linqFilter.Dump();

 var predicate = PredicateBuilder.False<Orders>();
 predicate = (linqFilter);
 var dynamicResult = from o in Orders.Where(predicate) select o;
 dynamicResult.Dump();

回答1:


Okay try something like this.

 var predicate = PredicateBuilder.False<Orders>();
 predicate = predicate.And(o => o.OrderID >= 100);
 var dynamicResult = from o in Orders.Where(predicate) select o;

As you have said you used linqfilter string. it means you needs to build expression dynamically. So for that here is one good article in codeproject. For you refer "Dynamic Where" section in that article. You definitely get the hint from that section.



来源:https://stackoverflow.com/questions/25702926/using-a-string-where-clause-with-predicatebuilder-in-linqpad-for-creating-dynami

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!