我如何在实体框架中查询空值? [英] How can i query for null values in entity framework?

查看:104
本文介绍了我如何在实体框架中查询空值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想执行这样的查询

   var result = from entry in table
                     where entry.something == null
                     select entry;

并获得 IS NULL 生成。

编辑:
在第一个两个答案之后,我觉得需要澄清一点:我正在使用Entity Framework
而不是Linq to SQL。 object.Equals()方法在EF中似乎不起作用。

Edited: After the first two answers i feel the need to clarify that I'm using Entity Framework and not Linq to SQL. The object.Equals() method does not seem to work in EF.

编辑no.2:
上述查询按预期方式工作。它正确地生成 IS NULL 。我的生产代码是

Edit no.2: The above query works as intended. It correctly generates IS NULL. My production code however was

value = null;
var result = from entry in table
                         where entry.something == value
                         select entry;

,生成的SQL是 something = @p; @p = NULL 。看来,EF正确地转换了常量表达式,但是如果涉及到一个变量,它就像一个正常的比较一样对待它。实际上是有意义的。我会关闭这个问题

and the generated SQL was something = @p; @p = NULL. It seems that EF correctly translates the constant expression but if a variable is involved it treats it just like a normal comparison. Makes sense actually. I'll close this question

推荐答案

Linq-to-SQL的解决方法:

Workaround for Linq-to-SQL:

var result = from entry in table
             where entry.something.Equals(value)
             select entry;

Linq-to-Entities(ouch!)的解决方法:

Workaround for Linq-to-Entities (ouch!):

var result = from entry in table
             where (value == null ? entry.something == null : entry.something == value)
             select entry;

这是一个令人讨厌的错误,已经咬了我几次。 如果这个错误也影响了你,请访问,并让Microsoft知道这个错误也影响了您。罢工>

This is a nasty bug which has bitten me several times. If this bug has affected you too, please visit the bug report on UserVoice and let Microsoft know that this bug has affected you as well.

编辑: 这个bug在EF 4.5中修复!感谢大家升级这个错误!

This bug is being fixed in EF 4.5! Thanks everyone for upvoting this bug!

为了向后兼容,它将被选择加入 - 您需要手动启用一个设置来使 entry ==值工作。这个设置什么都没有。请保持关注!

For backwards compatibility, it will be opt-in - you need manually enable a setting to make entry == value work. No word yet on what this setting is. Stay tuned!

编辑2:根据这篇文章由EF团队,这个问题已经在EF6中修复了! Woohoo!


我们更改了EF6的默认行为以补偿三值逻辑。

We changed the default behavior of EF6 to compensate for three-valued logic.

这意味着现有的代码依赖于旧的行为 null!= null 只有当与变量进行比较时)将需要更改为不依赖该行为,或设置

This means that existing code that relies on the old behavior (null != null, but only when comparing to a variable) will either need to be changed to not rely on that behavior, or set UseCSharpNullComparisonBehavior to false to use the old broken behavior.

这篇关于我如何在实体框架中查询空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆