代码之家  ›  专栏  ›  技术社区  ›  Retrocoder

将Linq表达式作为字符串传递?

  •  3
  • Retrocoder  · 技术社区  · 14 年前

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

    我想做的是传入Where子句中的表达式。我看到它可能需要一个字符串,但下面抛出了一个错误:

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

    运行时的错误消息是查询语法无效。近期'>',第6行,第4列。;传入最初从字符串派生的表达式的最佳方法是什么?

    3 回复  |  直到 14 年前
        1
  •  3
  •   leppie    14 年前

    必须手动构建表达式。

    IIRC,在LINQ101示例中有一个DynamicExpressions库可以为您完成这项工作。

        2
  •  2
  •   fearofawhackplanet    14 年前

    我不认为 Where 可以将字符串作为参数。 Dynamic Linq 允许您以字符串形式传递查询,但可能不是以上面尝试的特定格式。这取决于你到底想达到什么目的,也许值得一看。

        3
  •  2
  •   Glorfindel RaphaMex    5 年前

    dynamic linq sample 除了去掉lambda符号外,我们可以做很多事情:

    String expression = "Device == \"TEST\"" ;
    
    //... etc
    
        .Where(expression)
    

    alt text
    (来源: scottgu.com )