Cannot make a dynamic LINQ query work
Options
I am using the following dynamic query in LinqPad with PredicateBuilder enabled. You can enable this by pressing F4 and then checking the check-box in bottom right of the popup.
The query throws this error when I try to execute it: Cannot implicitly convert type 'string' to 'System.Linq.Expressions.Expression>'
Question: What is the problem with my dynamic LINQ query below? I had C#Expressions selected from LinqPad drop-down.
I am trying to dynamically build a where condition for a LINQ query. Query is based on standard Northwind database.
The query throws this error when I try to execute it: Cannot implicitly convert type 'string' to 'System.Linq.Expressions.Expression>'
Question: What is the problem with my dynamic LINQ query below? I had C#Expressions selected from LinqPad drop-down.
I am trying to dynamically build a where condition for a LINQ query. Query is based on standard Northwind database.
<code>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
Comments
-
PredicateBuilder can't do exactly what you want here. As the exception says, you need an Expression not a string. And the operator can't be dynamic. The following would be the closest:
int? orderParam = 100; string orderOperator = ">="; var predicate = PredicateBuilder.True<Orders>(); if(orderOperator == ">=") predicate = predicate.And(a => a.OrderID >= orderParam); var result = from o in Orders.Where(predicate) select o; result .Dump();
Running in C# Statement(s) is required for this code.