在LinqPad中将字符串where子句与PredicateBuilder一起使用以创建动态where子句 [英] Using a string where clause with PredicateBuilder in LinqPad for creating dynamic where clause

查看:121
本文介绍了在LinqPad中将字符串where子句与PredicateBuilder一起使用以创建动态where子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在启用了PredicateBuilder的LinqPad中创建动态查询.

I am trying to create a dynamic query in LinqPad with PredicateBuilder enabled.

我首先创建一个字符串,该字符串与(orderid> 100 AND customerid< = 100)"之类的查询的where子句相对应,然后尝试使用此字符串在PredicateBuilder中构建LINQ查询.动态查询由本文末尾给出的代码中的变量'dynamicResult'表示.该查询位于SQL Server 2008 R2中Northwind数据库的Orders表上.

I first create a string that corresponds to the where clause for a query like '(orderid >100 AND customerid<=100)' and then try to use this string in building a LINQ query with PredicateBuilder. The dynamic query is represented by the variable 'dynamicResult' in code give at end of this post. The query is on Orders table of Northwind database in SQL Server 2008 R2.

当我尝试执行查询时,该查询在LinqPad中引发此错误:

The query throws this error in LinqPad, when I try to execute it:

无法将类型'string'隐式转换为 'System.Linq.Expressions.Expression>'

Cannot implicitly convert type 'string' to 'System.Linq.Expressions.Expression>'

问题:我如何在PredicateBuilder中使用类似于(orderid> 100 AND customerid< = 100)"之类的字符串的过滤器?尝试执行以下代码时,我从LinqPad中选择了"C#语句".

Question: How can I use a filter that is a string like '(orderid >100 AND customerid<=100)' with PredicateBuilder ? I had 'C# Statements' selected from LinqPad when trying to execute the below code.

我正在尝试为LINQ查询动态建立一个where条件.

I am trying to dynamically build a where condition for a LINQ query.

int? orderParam = 100;
string orderOperator = ">=";
string linqFilter = "";
linqFilter= String.Format("{0} {1} {2}", "o.OrderID", orderOperator, orderParam);
linqFilter.Dump();

 var predicate = PredicateBuilder.False<Orders>();
 predicate = (linqFilter);
 var dynamicResult = from o in Orders.Where(predicate) select o;
 dynamicResult.Dump();

推荐答案

好的,尝试这样的事情.

Okay try something like this.

 var predicate = PredicateBuilder.False<Orders>();
 predicate = predicate.And(o => o.OrderID >= 100);
 var dynamicResult = from o in Orders.Where(predicate) select o;

正如您所说的,您使用了 linqfilter 字符串.这意味着您需要动态构建表达式.因此,这里有一篇代码项目.您可以参考该文章中的动态位置" 部分.您绝对可以从该部分获得提示.

As you have said you used linqfilter string. it means you needs to build expression dynamically. So for that here is one good article in codeproject. For you refer "Dynamic Where" section in that article. You definitely get the hint from that section.

这篇关于在LinqPad中将字符串where子句与PredicateBuilder一起使用以创建动态where子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆