为什么LINQ生成的SQL包含多个“IS NULL"?同一列的条件

Why does LINQ generated SQL include multiple quot;IS NULLquot; conditions for the same column(为什么LINQ生成的SQL包含多个“IS NULL?同一列的条件)
本文介绍了为什么LINQ生成的SQL包含多个“IS NULL"?同一列的条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下针对 SQL Server 2012 数据库的查询,使用 Entity Framework Core 3.1:

The following query against a SQL Server 2012 database, using Entity Framework Core 3.1:

        var tows = await _context.DataEntryTow
            .Where(t => _context.DataEntrySample
                        .Any(s => s.TowId==t.TowId && (s.MicroscopeId != "0" || s.MicroscopeId == null)))
            .Select (t => new { text = t.TowId, value = t.TowId });

生成此 SQL:

SELECT d.tow_id AS text
FROM data_entry_tow AS d
WHERE EXISTS (
    SELECT 1
    FROM data_entry_sample AS d0
    WHERE (d0.tow_id = d.tow_id) AND (((d0.microscope_id <> '0') OR (d0.microscope_id IS NULL)) OR (d0.microscope_id IS NULL)))

我不认为我做错了什么,我相当确定查询优化器会消除第二个(d0.microscope_id IS NULL),但它似乎仍然是 LINQ 代码中的错误.

I don't think I've done anything wrong, and I'm fairly sure the query optimizer will eliminate the second (d0.microscope_id IS NULL), but it still seems like an error in the LINQ code.

MicroscopeId 已定义:

    public string MicroscopeId { get; set; }

推荐答案

Field MicroscopeId 声明为可为空.因此,当 null != "0"true 但在 SQL null <> 中时,要模仿 LINQ to Objects 的行为.'0' 为假,EF Core 生成额外的 OR 条件.

Field MicroscopeId declared as nullable. So, to mimic LINQ to Objects behaviour when null != "0" is true but in SQL null <> '0' is false, EF Core generates additional OR condition.

要禁用此生成,您必须在构建 DbContextOptions 时指定:

To disable this geneeration you have to specify that when building DbContextOptions:

optionsBuilder.UseSqlServer(constr, b => b.UseRelationalNulls(true) );

附加信息:https://docs.microsoft.com/en-us/ef/core/querying/null-comparisons#using-relational-null-semantics

这篇关于为什么LINQ生成的SQL包含多个“IS NULL"?同一列的条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
SSIS: Model design issue causing duplications - can two fact tables be connected?(SSIS:模型设计问题导致重复-两个事实表可以连接吗?)
SQL Server Graph Database - shortest path using multiple edge types(SQL Server图形数据库-使用多种边类型的最短路径)
Invalid column name when using EF Core filtered includes(使用EF核心过滤包括时无效的列名)
How should make faster SQL Server filtering procedure with many parameters(如何让多参数的SQL Server过滤程序更快)
How can I generate an entity–relationship (ER) diagram of a database using Microsoft SQL Server Management Studio?(如何使用Microsoft SQL Server Management Studio生成数据库的实体关系(ER)图?)