C # – Pass the LINQ expression as a string?

The following code works fine

using (var ctx = new MyEntities())
{
var devices = ctx.Devices
.Where(x=> x.Device == "TEST")
.ToList();
return devices;
}

What I want to do is to pass in the expression in the “Where” clause. I see that it may require a string, but the following raises an error:

String expression = "x=> x.Device == \"TEST\"" ;

using (var ctx = new MyEntities())
{
var devices = ctx.Devices
.Where(expression)
.ToList();
return devices;
}

The error message at runtime is “Invalid query syntax .Recently’>’, line 6, column 4. “; What is the best way to pass an expression originally derived from a string?

You must manually construct the expression.

IIRC,LINQ101 There is a DynamicExpressions library in the sample that can complete this task for you.

The following code works fine

 using (var ctx = new MyEntities())
{
var devices = ctx.Devices
.Where(x=> x.Device == "TEST")
.ToList ();
return devices;
}

What I want to do is to pass in the expression in the “Where” clause. I see that it may require a string, But the following throws an error:

String expression = "x=> x.Device == \"TEST\"" ;

using (var ctx = new MyEntities())
{
var devices = ctx.Devices
.Where(expression)
.ToList();
return devices;
}

The error message at runtime is “The query syntax is invalid. Recent’>’, line 6, column 4.”; What is the best way to pass the expression originally derived from the string?

You have to build the expression manually.

IIRC, there is a DynamicExpressions library in the LINQ101 sample, which can do this for you Task.

Leave a Comment

Your email address will not be published.