gpt4 book ai didi

c# - LINQ to Entities 和空字符串

转载 作者:可可西里 更新时间:2023-11-01 03:13:25 30 4
gpt4 key购买 nike

我在使用 EF 4.0 作为其数据库后端的 ASP.NET 4.0 Web 应用程序上发生了一件很奇怪的事情。本质上,我有一个存储用户密码重置请求的表(包含 byte[] 类型的重置 key 、DateTime 类型的到期时间和外键到包含 string Emailstring NameUser)。一些用户没有设置电子邮件地址,因此对于 PasswordRequest 请求request.Emailnull

问题来了。这工作得很好:

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 电子邮件的条目)。

但是当 enull 时,这总是返回一个空集合:

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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com