[英]DateTime lambda expressions
I was testing the implementation in the thread answer https://stackoverflow.com/a/7891426/1468492 but I get an error trying to parse an expression with a DateTime
, for instance: t => t.Name == "NAME" && t.OpeningDate == DateTime.Now
. 我在线程回答https://stackoverflow.com/a/7891426/1468492中测试实现,但是在尝试使用
DateTime
解析表达式时遇到错误,例如: t => t.Name == "NAME" && t.OpeningDate == DateTime.Now
。
Is this the right way to build a DateTime lambda expression? 这是构建DateTime lambda表达式的正确方法吗? If I create an expression like
Expression<Func<Model, bool>> expression = t => t.Name == "NAME"
the result is correct. 如果我创建一个表达式,例如
Expression<Func<Model, bool>> expression = t => t.Name == "NAME"
则结果正确。
Is there something wrong? 有什么不对?
You need to improve current solution to support members, particularly you need to improve VisitMember
. 您需要改进当前的解决方案以支持成员,特别是需要改进
VisitMember
。 Now it just throws a NotSupportedException
. 现在,它仅抛出
NotSupportedException
。
As a workaround you can just extract it first: 作为解决方法,您可以先提取它:
DateTime now = DateTime.Now;
var expression = t => t.Name == "NAME" && t.OpeningDate == now;
In this case it would address a constant, not a member. 在这种情况下,它将处理常量而不是成员。
If you can build t => t.Name == "NAME"
expression, the next step is to combine it with t.OpeningDate == DateTime.Now
by Expression.And
. 如果可以构建
t => t.Name == "NAME"
表达式,则下一步是将其与t.OpeningDate == DateTime.Now
通过Expression.And
。 Try this code: 试试这个代码:
var t = Expression.Parameter(typeof(Model), "t");
var body = Expression.And(
Expression.Equal(Expression.PropertyOrField(t, "Name"), Expression.Constant("NAME")),
Expression.Equal(Expression.PropertyOrField(t, "OpeningDate"), Expression.Constant(DateTime.Now))
);
var predicate = Expression.Lambda<Func<Model, bool>>(body, t);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.