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

Dav*_*ght 15 .net c# linq linq-to-entities entity-framework

我正在写一些LINQ来根据电子邮件获取记录,但是,生成的SQL包含一个附加IS NULL条件,不需要在那里,因为我在将条件添加到代码之前检查代码中的null参数值查询.

我的LINQ代码是:

if (email != null)
{
    query = query.Where(r => r.Email == email);
}
Run Code Online (Sandbox Code Playgroud)

由此生成的SQL条件是:

(([Extent1].[Email] = @p__linq__0) OR (([Extent1].[Email] IS NULL) AND (@p__linq__0 IS NULL)))
Run Code Online (Sandbox Code Playgroud)

(([Extent1].[Email] IS NULL) AND (@p__linq__0 IS NULL))
Run Code Online (Sandbox Code Playgroud)

就我所见,我不需要在那里.

有没有办法让LINQ省略它?

Nic*_*las 24

他们在那里以防万一email.

您可以通过将UseDatabaseNullSemantics设置为来防止这种情况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);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果要将其应用于所有查询:

public class TheContext : DbContext
{
    public TheContext()
    {
        this.Configuration.UseDatabaseNullSemantics = true;
    }
}
Run Code Online (Sandbox Code Playgroud)

您还可以将属性更改为[Required]:

public class Model {
    [Required]
    public string Email { get; set; }
}
Run Code Online (Sandbox Code Playgroud)