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

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

问题描述

我想执行这样的查询

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

并生成一个IS NULL.

在前两个答案之后,我觉得有必要澄清我正在使用实体框架而不是 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.

编辑 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 will 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 的解决方法(哎哟!):

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

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

这是一个讨厌的虫子,它已经咬了我好几次了.如果此错误也影响到您,请访问 关于 UserVoice 的错误报告 并让 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.

此错误已在 EF 4.5 中修复!感谢大家为这个 bug 点赞!

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

为了向后兼容,它将选择加入 - 您需要手动启用设置以使 entry == value 工作.目前还没有关于这个设置是什么的消息.敬请期待!

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 中修复!哇哦!

Edit 2: According to this post by the EF team, this issue has been fixed in EF6! Woohoo!

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

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

这意味着依赖于旧行为的现有代码(null != null, but only when compare to a variable)要么需要更改为不依赖该行为,或设置 UseCSharpNullComparisonBehavior 为 false 以使用旧的损坏行为.

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天全站免登陆