问题描述
我有一种方法可以为给定类型,属性和值的LINQ查询构建表达式.只要类型上的属性不可撤消,这种效果就可以很好地起作用.这是我正在工作的示例( http:http://wwwww .marcuswhitworth.com/2009/12/dynamic-linq-with-expression-trees )我在属性上调用了equals方法.但是,我已经发现,无效类型的等效方法将对象作为参数而不是可无效的类型.我试图使用getValueorDefault隐藏空值,但EF不支持该方法.作为一个简单的示例,以下代码将引发错误:
decimal? testVal = new decimal?(2100); var test = (from i in context.Leases where i.AnnualRental.Equals(testVal) select i).ToList();
但是,如果您使用==而不是equals()方法,则可以正常工作.我不确定如何将代码转换为使用==而不是equals().任何建议都将不胜感激.
推荐答案
如果您说==,则将BinaryExpression产生为ExpressionType.Equal. http://msdn.microsoft.com/en-us/en-us/library/library/library/bb361179.aspx
如果您说.Equals(x),则会生成MethodCallExpression. LinQtoTenities可能转化为SQL的MethodCallExpression是一个限制列表(例如,您自己的未装饰方法都不在该列表中). Nullable<T>.Equals(x)显然不在该列表中.
不要对linqtoentities说.Equals(x)
问题描述
I have a method to build an expression for a linq query for a given type, property, and value. This works wonderfully as long as the property on the type is NOT nullable. Here is the example I am working from (http://www.marcuswhitworth.com/2009/12/dynamic-linq-with-expression-trees) I am calling the Equals method on the property. However I have discovered that the Equals method for Nullable types takes an Object as a parameter instead of the Nullable type. I attempted to use GetValueOrDefault to hide the null values but EF doesn't support that method. As a simple example the following code will throw an error:
decimal? testVal = new decimal?(2100); var test = (from i in context.Leases where i.AnnualRental.Equals(testVal) select i).ToList();
However if you use == instead of the Equals() method it will work OK. I am not sure how to convert the code to use == instead of Equals() however. Any suggestions will be greatly appreciated.
推荐答案
If you say ==, you generate a BinaryExpression with NodeType as ExpressionType.Equal. http://msdn.microsoft.com/en-us/library/bb361179.aspx
If you say .Equals(x), you generate a MethodCallExpression. The MethodCallExpressions that LinqToEntities may translate into Sql is a limitted list (for example none of your own undecorated methods are in that list). Nullable<T>.Equals(x) is apparently not on that list.
Don't say .Equals(x) to LinqToEntities.