如何构建含Substring的LINQ Expression Tree实现指定SQL查询?
解决方案
问题还原(翻译后)
我想要创建如下SQL LINQ表达式:
.Where(product => product.name.Substring(3,5).Contains("ma")
请问有人能帮我实现这个表达式吗?我尝试使用如下代码:
Expression.PropertyOrField(body, "name.Substring(3,5)");
但出现了错误:
Substring(3,5) is not a member of type 'System.String'
错误原因
你错误地将name.Substring(3,5)当作了对象的属性/字段,但Substring是string类型的方法,不是属性或字段,Expression.PropertyOrField只能识别对象的成员属性/字段,无法直接解析方法调用,因此抛出错误。
正确实现步骤
要构建目标表达式树,需要分三步嵌套方法调用:
- 获取
product.name的表达式节点 - 调用
name的Substring(3,5)方法 - 调用
Substring返回值的Contains("ma")方法
完整代码示例
假设body是代表product的参数表达式(比如ParameterExpression productParam = Expression.Parameter(typeof(Product), "product");),代码如下:
// 1. 获取product.name的表达式 Expression nameExpr = Expression.PropertyOrField(body, "name"); // 2. 构建Substring方法调用(参数:startIndex=3,length=5) MethodInfo substringMethod = typeof(string).GetMethod("Substring", new[] { typeof(int), typeof(int) }); Expression substringExpr = Expression.Call( nameExpr, substringMethod, Expression.Constant(3), Expression.Constant(5) ); // 3. 构建Contains方法调用(参数:"ma") MethodInfo containsMethod = typeof(string).GetMethod("Contains", new[] { typeof(string) }); Expression containsExpr = Expression.Call( substringExpr, containsMethod, Expression.Constant("ma") ); // 生成最终的Lambda表达式,用于Where方法 var whereLambda = Expression.Lambda<Func<Product, bool>>(containsExpr, body);
内容的提问来源于stack exchange,提问作者Esha Kheni
相关产品推荐
相关产品推荐

