日期:2014-05-20  浏览次数:20988 次

Linq动态查询--Expression.LessThan问题.
right = Expression.Constant(Convert.ToDateTime(outTime));
right = Expression.Convert(right, typeof(DateTime));
left = Expression.Property(param, typeof(Table1).GetProperty("OutOfTime"));
filter = Expression.LessThan(left, right);

其中OutOfTime字段在Table1表中为DateTime类型并且为可空,这时问题来了。
Expression.LessThan拼接filter时说"The binary operator Equal is not defined for the types 'System.Nullable`1[System.DateTime]' and 'System.DateTime'."
自己搜了半天,搜到的结果都说这个错误是由于Expression的两边都必须为同一类型导致(the expression tree needs both sides of the expression to be the same type)。不太明白,OutOfTime此时明明不为空,为什么不能比较?
不光LessThan,LessThanOrEqual、GreaterThan、GreaterThanOrEqual也存在相同问题。
如何解决?请各位高人不吝赐教,谢谢。

------解决方案--------------------
DateTime? left;
DateTime right;

left < right
你觉得这能编译么?解决方案一样。
------解决方案--------------------
我从来不使用 Linq.Expressions。如果你只是应用Linq的高级功能,而不是觉得它实在太差了需要你动手从内部重构它,最好不要写这类代码。

如果你写成 linq 查询表达式,或许可以帮你看看。