LINQ 在 SQL 语句中生成额外的 IS NULL 条件

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

来防止这种情况

Gets or sets a value indicating whether database null semantics are exhibited when comparing two operands, both of which are potentially nullable. The default value is false. For example (operand1 == operand2) will be translated as: (operand1 = operand2) if UseDatabaseNullSemantics is true, respectively (((operand1 = operand2) AND (NOT (operand1 IS NULL OR operand2 IS NULL))) OR ((operand1 IS NULL) AND (operand2 IS NULL))) if UseDatabaseNullSemantics is 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; }
}