相同的linq查询在不同的项目

时间:2015-05-19 21:28:54

标签: c# linq entity-framework

查询是:

        var query =
                from stokHareket1 in ce.StokHarekets
                from stokHareket2 in ce.StokHarekets
                join stok in ce.Stoks on stokHareket1.StokId equals stok.Id
                where (
                stokHareket1.StokId == stokHareket2.StokId
                )
                select new
                {
                    result = stokHareket1.StokId
                };

在第一个项目中,EF版本为: 5.0.0 ,在第二个项目中: 6.1.3

它在第一个项目中给出:

SELECT 
[Extent1].[StokId] AS [StokId]
FROM  [dbo].[StokHareket] AS [Extent1]
INNER JOIN [dbo].[StokHareket] AS [Extent2] ON [Extent1].[StokId] = [Extent2].[StokId]
WHERE [Extent1].[StokId] IS NOT NULL

在第二个:

SELECT 
[Extent1].[StokId] AS [StokId]
FROM  [dbo].[StokHareket] AS [Extent1]
INNER JOIN [dbo].[StokHareket] AS [Extent2] ON ([Extent1].[StokId] = [Extent2].[StokId])   
/*THIS LINE*/OR (([Extent1].[StokId] IS NULL) AND ([Extent2].[StokId] IS NULL)) 
WHERE [Extent1].[StokId] IS NOT NULL

/*THIS LINE*/不同

这种差异可能是什么原因?

为了更好地可视化,这里是屏幕截图:

在db,stokHareket表中

enter image description here

在Edmx:

enter image description here

1 个答案:

答案 0 :(得分:5)

这似乎是EF6中引入的变化(可能更早;我还没有找到确凿的证据)。 EF6开始将SQL空值比较规则(null == null为真)注入SQL查询,除非您将上下文配置中的UseDatabaseNullSemantics属性设置为true

public class MyContext : DbContext
{
    public MyContext()
    {
        this.Configuration.UseDatabaseNullSemantics = true;
    }
}

在任何情况下,它都不会影响您的结果 - WHERE子句会过滤掉StokId为空的任何记录。