Search code examples
c#linq-to-entities

Passing a 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 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 is 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?


Solution

  • You have to build the Expression manually.

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