本文介绍了实体框架-Linq-无法创建类型为"System.Object"的常量.仅原始类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种方法可以为给定类型,属性和值的linq查询构建表达式.只要该类型上的属性不可为空,它就可以很好地工作.这是我正在使用的示例( http://www .marcuswhitworth.com/2009/12/dynamic-linq-with-expression-trees ),我正在对该属性调用Equals方法.但是,我发现Nullable类型的Equals方法将Object作为参数而不是Nullable类型.我试图使用GetValueOrDefault隐藏空值,但EF不支持该方法.作为一个简单的示例,以下代码将引发错误:

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();

但是,如果使用==代替Equals()方法,它将可以正常运行.我不确定如何将代码转换为使用==而不是Equals().任何建议将不胜感激.

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.

推荐答案

如果说==,则会生成一个NodeType为ExpressionType.EqualBinaryExpression. http://msdn.microsoft.com/en-us/library/bb361179.aspx

If you say ==, you generate a BinaryExpression with NodeType as ExpressionType.Equal. http://msdn.microsoft.com/en-us/library/bb361179.aspx

如果您说.Equals(x),则会生成一个MethodCallExpression. LinqToEntities可以转换为Sql的MethodCallExpression是一个受限列表(例如,该列表中没有您自己的未修饰方法). Nullable<T>.Equals(x)显然不在该列表中.

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.

不要对LinqToEntities说.Equals(x).

Don't say .Equals(x) to LinqToEntities.

这篇关于实体框架-Linq-无法创建类型为"System.Object"的常量.仅原始类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 17:13