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.

WordPress database error: [Table 'yf99682.wp_s6mz6tyggq_comments' doesn't exist]
SELECT SQL_CALC_FOUND_ROWS wp_s6mz6tyggq_comments.comment_ID FROM wp_s6mz6tyggq_comments WHERE ( comment_approved = '1' ) AND comment_post_ID = 3039 ORDER BY wp_s6mz6tyggq_comments.comment_date_gmt ASC, wp_s6mz6tyggq_comments.comment_ID ASC

Leave a Comment

Your email address will not be published.