问题
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