【发布时间】:2017-04-06 06:19:42
【问题描述】:
我正在使用 LINQ 表达式生成一个 where 条件。
我的实体如下;
public class Sample
{
public int Id { get; set; }
public string Name { get; set; }
public int AnotherId { get; set; }
public int? RelationId { get; set; }
}
我必须根据两个键过滤数据,即AnotherId 和RelationId.RelationId(可选)。所以在我的方法参数relationId可能不会更新为0。
基于此我需要生成一个表达式:
Expression<Func<Sample, bool>> condition = x => x.AnotherId == anotherId;
if (relationId > 0)
{
Expression<Func<Sample, bool>> additionalCondition = x => x.RelationId == relationId;
condition = Expression.Lambda<Func<Sample, bool>>(Expression.AndAlso(condition, additionalCondition), condition.Parameters);
}
这里我在AndAlso 语句中得到了以下异常:
没有为“System.Func`2[Sample,System.Boolean]”和“System.Func`2[Sample,System.Boolean]”类型定义二元运算符 AndAlso。
请帮我纠正我的问题。
【问题讨论】:
-
查看this链接
-
我认为
condition = Expression.Lambda<Func<Sample, bool>>(Expression.AndAlso(condition.Body, additionalCondition.Body), condition.Parameters);应该可以工作 -
只是
x.AnotherId == anotherId && (!relationId>0 || x.RelationId==relationId)吗? -
@kienct89 我检查并添加了该扩展方法,但过滤器不起作用。
-
@RobertMcKee 效果很好。一个小小的改变 x.AnotherId == anotherId && (!(relationId>0) || x.RelationId==relationId)。但是为什么这种表达方法不起作用呢?