- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我在使用 EF 4.0 作为其数据库后端的 ASP.NET 4.0 Web 应用程序上发生了一件很奇怪的事情。本质上,我有一个存储用户密码重置请求的表(包含 byte[]
类型的重置 key 、DateTime
类型的到期时间和外键到包含 string Email
和 string Name
的 User
)。一些用户没有设置电子邮件地址,因此对于 PasswordRequest 请求
,request.Email
为 null
。
问题来了。这工作得很好:
string u = Request["u"];
string e = Request["e"];
var requests = from r in context.PasswordRequests
where r.User.Name == u && r.User.Email == null && r.Expiry >= DateTime.Now
select r;
我得到了预期数量的结果(非零,因为有包含 null
电子邮件的条目)。
但是当 e
为 null
时,这总是返回一个空集合:
string u = Request["u"];
string e = Request["e"];
var requests = from r in context.PasswordRequests
where r.User.Name == u && r.User.Email == e && r.Expiry >= DateTime.Now
select r;
我唯一能正常工作的(这在逻辑上没有任何意义)是:
string u = Request["u"];
string e = Request["e"];
IQueryable<PasswordRequest> requests;
if (e == null)
requests = from r in context.PasswordRequests
where r.User.Name == u && r.User.Email == null && r.Expiry >= DateTime.Now
select r;
else
requests = from r in context.PasswordRequests
where r.User.Name == u && r.User.Email == e && r.Expiry >= DateTime.Now
select r;
我完全被难住了。有什么想法吗?
最佳答案
基本上,在处理空值时,这是 SQL 和 C# 之间的不匹配。您不需要使用两个查询,但您需要:
where r.User.Name == u && (r.User.Email == e ||
(e == null && r.User.Email == null))
这很烦人,可能有一个辅助函数可以让生活更轻松,但它从根本上来自于 SQL 的空处理,其中
where X = Y
如果 X 和 Y 都为空,
将不匹配。 (而在 C# 中,等效表达式为真。)
您可能还需要对 u
执行相同的操作,除非它在数据库中不可为空。
如果您对以相同方式处理 null 和空字符串感到满意,您至少可以尝试的一个小技巧是:
// Before the query
e = e ?? "";
// In the query
where r.User.Name == u && (r.User.Email ?? "") == e
我相信这将对电子邮件列和 e
执行 null 合并,因此您永远不会将 null 与任何内容进行比较。
关于c# - LINQ to Entities 和空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8090894/
我正在尝试创建一个程序,其中字符串的前三个字符重复给定次数,如下所示: foo('Chocolate', 3) # => 'ChoChoCho' foo('Abc', 3) # => 'AbcAbcA
我有以下字符串: std::string str = "Mode:AAA:val:101:id:A1"; 我想分离一个位于 "val:" 和 ":id" 之间的子字符串,这是我的方法: std::st
DNA 字符串可以是任意长度,包含 5 个字母(A、T、G、C、N)的任意组合。 压缩包含 5 个字母(A、T、G、C、N)的 DNA 字母串的有效方法是什么?不是考虑每个字母表 3 位,我们可以使用
是否有一种使用 levenstein 距离将一个特定字符串与第二个较长字符串中的任何区域进行匹配的好方法? 例子: str1='aaaaa' str2='bbbbbbaabaabbbb' if str
使用 OAuth 并使用以下函数使用我们称为“foo”(实际上是 OAuth token )的字符串加密 key public function encrypt( $text ) { // a
我是一名优秀的程序员,十分优秀!