开发者

Passing a Linq expression as a string?

开发者 https://www.devze.com 2023-01-07 17:06 出处:网络
The following code works fine using (var ctx = new MyEntities()) { var devices = ctx.Devices .Where(x=> x.Device == \"TEST\")

The following code works fine

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

What I would like to do is to pass in the expression that goes in the “Where” clause. I see that it can take 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 i开发者_如何学Cs not valid. Near term '>', line 6, column 4.”; What would be the best way to pass in an expression that is initially derived from a string?


You have to build the Expression manually.

IIRC, there is a DynamicExpressions library in the LINQ101 samples that can do this for you.


I don't think Where can take a string as parameter. Dynamic Linq lets you pass queries as strings, though probably not in the specific format you're trying to do above. Depending on what exactly it is you are trying to achieve, it might be worth a look.


The dynamic linq sample can do much of this, except you drop the lambda notation:

String expression = "Device == \"TEST\"" ;

//... etc

    .Where(expression)

Another example (from the blog):

Passing a Linq expression as a string?


(source: scottgu.com)

0

精彩评论

暂无评论...
验证码 换一张
取 消