UseDatabaseNullSemantics仍然生成NULL检查

时间:2016-03-09 18:59:26

标签: sql linq

我在我的上下文对象(构造函数)上有这个:

this.Configuration.UseDatabaseNullSemantics = true;

但即使使用此设置,此查询:

var query = (from i in _repo.Invoices
             join o in _repo.Orders on i.orderid equals o.orderid
             join o2 in _repo.Orders on o.linkedorderid equals o2.linkedorderid  into leftOrders
             from lo in leftOrders.DefaultIfEmpty()
             where invoiceIds.Contains(i.invoiceid)
             select new
             {
                i, lo
             }).ToList();

返回此SQL:

SELECT 
    [Extent1].[invoiceid] AS [invoiceid], 
    [Extent1].[custid] AS [custid], 
    [Extent1].[orderid] AS [orderid], 
    [Extent1].[orderamount] AS [orderamount], 
    [Extent1].[invoiceamount] AS [invoiceamount], 
    [Extent1].[paidamount] AS [paidamount], 
    [Extent1].[paidstatus] AS [paidstatus], 
    [Extent1].[printdate] AS [printdate], 
    [Extent1].[updateddate] AS [updateddate]
    FROM   [dbo].[invoices] AS [Extent1]
    INNER JOIN [dbo].[orders] AS [Extent2] ON [Extent1].[orderid] = [Extent2].[orderid]
    LEFT JOIN [dbo].[orders] AS [Extent3] ON ([Extent2].[linkedorderid] = [Extent3].[linkedorderid]) OR (([Extent2].[linkedorderid] IS NULL) AND ([Extent3].[linkedorderid] IS NULL))
    WHERE [Extent1].[invoiceid] IN (3098489, 3123185, 3156838)

我很难看到我收到System.OutOfException错误,因为我有大量订单,其中linkedorderid等于NULL。

如果我删除OR (([Extent2].[linkedorderid] IS NULL) AND ([Extent3].[linkedorderid] IS NULL))查询运行正常并返回所有包含子工单的发票......

我知道如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

这有用吗?如果删除(或(是null并且为null))子句时发布的查询是正确的,那么我认为这将执行相同的查询。 (这假设连接中没有逻辑错误,如其他帖子所示。)

var query = (from i in _repo.Invoices
    from o in _repo.Orders.Where(c => c.orderid == i.orderid)
    from o2 in _repo.Orders.Where(c => c.linkedorderid == o.linkedorderid).DefaultIfEmpty()                          
    where invoiceIds.Contains(i.invoiceid)
    select new
    {
       i, o2
    }).ToList();

答案 1 :(得分:0)

您在生成的SQL中看到的条件与UseDatabaseNullSemantics没有任何共同之处,需要使用可以为空的键正确处理LEFT LOIN

我认为您遇到的问题是由查询中的逻辑错误引起的。 IMO,加入条件

on o.linkedorderid equals o2.linkedorderid

应该是

on o.linkedorderid equals o2.orderid

因为通常 FK PK 相关联()。