简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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