[英]LINQ is Generating Extra IS NULL Condition in SQL Statement
我正在写一些LINQ来根据电子邮件获取记录,但是,生成的SQL包含一个额外的IS NULL
条件,它不需要在那里,因为我在添加条件之前在代码中检查null的参数值到查询。
我的LINQ代码是:
if (email != null)
{
query = query.Where(r => r.Email == email);
}
由此生成的SQL条件是:
(([Extent1].[Email] = @p__linq__0) OR (([Extent1].[Email] IS NULL) AND (@p__linq__0 IS NULL)))
该
(([Extent1].[Email] IS NULL) AND (@p__linq__0 IS NULL))
就我所见,我不需要在那里。
有没有办法让LINQ省略它?
如果email
为空,他们就在那里。
您可以通过将UseDatabaseNullSemantics设置为true
来防止这种true
获取或设置一个值,该值指示在比较两个操作数时是否显示数据库空语义,这两个操作数都可能为空。 默认值为false。 例如(operand1 == operand2)将被翻译为:(operand1 = operand2)如果UseDatabaseNullSemantics分别为true(((operand1 = operand2)AND(NOT(operand1 IS NULL或operand2 IS NULL)))OR((operand1 IS) NULL)AND(operand2 IS NULL)))如果UseDatabaseNullSemantics为false。
有多种方法可以应用它。
如果您只想将其应用于单个查询,则可以执行以下操作:
using(TheContext dbContext = new TheContext()) {
dbContext.Configuration.UseDatabaseNullSemantics = true;
...
if (email != null)
{
query = query.Where(r => r.Email == email);
}
}
如果要将其应用于所有查询:
public class TheContext : DbContext
{
public TheContext()
{
this.Configuration.UseDatabaseNullSemantics = true;
}
}
您还可以将属性更改为[Required]
:
public class Model {
[Required]
public string Email { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.