在Odata Client中使用ParameterExpression创建动态查询

时间:2016-03-29 19:05:08

标签: c# linq odata iqueryable odata-v4

我使用Odata客户端代码生成器代理类消费Odata v4服务。

MetroContext = new MetroContainer(new Uri(@"http://localhost:56222/service"));
IQueryable<Patient> query = MetroContext.Patients;
query = query.Where(x => x.FirstName == "john");

以上代码工作正常。但我需要动态构建查询。所以我试过以下:

MetroContext = new MetroContainer(new Uri(@"http://localhost:56222/service"));
IQueryable<Patient> query = MetroContext.Patients;

ParameterExpression pe = Expression.Parameter(typeof(Patient), "patient");
Expression left = Expression.Property(pe, "FirstName");
Expression right = Expression.Constant("john");
Expression predicateBody = Expression.Equal(left, right);

query = query.Provider.CreateQuery<Patient>(predicateBody);

当我运行程序时,我收到错误消息:

  

将Linq表达式转换为URI时出错:二元运算符&#39; Equal&#39;   不受支持。

  • 为什么我收到此错误,我该如何解决?
  • 如何通过组合Contains()StartsWith()等方法来创建动态查询?

1 个答案:

答案 0 :(得分:2)

我无法测试该特定查询提供程序,但首先predicateBody不是任何提供程序的有效表达式。

相反,您需要构建Expression<Func<Patient, bool>>表达式并将其传递给Where方法,如下所示:

// ...
var predicate = Expression.Lambda<Func<Patient, bool>>(predicateBody, pe);
query = query.Where(predicate);

你的第二个问题是什么,你需要使用一些Expression.Call重载。例如:

Expression predicateBody = Expression.Call(left, "Contains", null, right);

类似于“StartsWith”和“EndWith”等。