为什么lambda表达式改变LEFT JOIN TO INNER JOIN当我把&&条件?

时间:2015-03-10 07:48:07

标签: .net linq tsql lambda

我喜欢生成左外连接查询,如下所示但不知何故我添加

  

&安培;&安培; o.sgd.intStoreGroup == intStoreGroup

进入lambda表达式,它从 LEFT JOIN更改为INNER JOIN。

以下lamdba表达中的任何错误?为什么会改变?我怎么解决呢?

模型

public partial class Partner_StoreTbl  
 {
        [Key]
        public int intStore { get; set; }
        public int intPartner { get; set; }
        public string varStoreRef { get; set; } 
        public byte tintStatus { get; set; }
 }

 public partial class Partner_StoreGroupDetailTbl 
{
    [Key]
    public int intStoreGroupDetail { get; set; }
    public int intStoreGroup { get; set; } 
    public int intStore { get; set; }

}

LINQ

List<byte> byteValue = new List<byte> { 1 };


var StoreGroupDetail = Partner_StoreTbl.GroupJoin(Partner_StoreGroupDetailTbl, s => s.intStoreRef, sgd => sgd.intStore, (s, sgd) => new { s, sgd })
    .Where(o=>o.s.intPartner==intPartner)
    .SelectMany(o => o.sgd.DefaultIfEmpty(), (s,sgd) => new { s.s,sgd}) 
    .Where(o => byteValue.Contains( o.s.tintStatus ) &&  o.sgd.intStoreGroup==intStoreGroup)
    .Select(o => new MODELS.ViewModels.Partner.StoreGroupDetail
    {
        intStoreRef = o.s.intStoreRef,
        intStoreGroup = o.sgd.intStoreGroup==null?0:o.sgd.intStoreGroup,


    }).ToList();

TSQL我想要LINQ生成

SELECT 
    [Extent1].[intStoreRef] AS [intStoreRef], 
    [Extent2].[intStoreGroup] AS [C1]
FROM  [dbo].[Partner_StoreTbl] AS [Extent1]
LEFT JOIN [dbo].[Partner_StoreGroupDetailTbl] AS [Extent2] ON [Extent1].[intStoreRef] = [Extent2].[intStore]  
    AND  [Extent2].[intStoreGroup] = 1
 WHERE ([Extent1].[intPartner] = 1) AND ([Extent1].[tintStatus] IN (cast(1 as tinyint))) 

但是我得到了这个

SELECT 
    [Extent1].[intStoreRef] AS [intStoreRef], 
    [Extent2].[intStoreGroup] AS [C1]
FROM  [dbo].[Partner_StoreTbl] AS [Extent1]
INNER JOIN [dbo].[Partner_StoreGroupDetailTbl] AS [Extent2] ON [Extent1].[intStoreRef] = [Extent2].[intStore]
WHERE ([Extent1].[intPartner] = @1) AND ([Extent1].[tintStatus] IN (cast(1 as tinyint))) AND ([Extent2].[intStoreGroup] = @1) 

1 个答案:

答案 0 :(得分:0)

对于

.GroupJoin(Partner_StoreGroupDetailTbl, s => s.intStoreRef, sgd => sgd.intStore, (s, sgd) => new { s, sgd })

你应该尝试

.GroupJoin(Partner_StoreGroupDetailTbl, s => new { intStore = s.intStoreRef, intStoreGroup = intStoreGroup }, sgd => new { intStore = sgd.intStore, sgd.intStoreGroup }, (s, sgd) => new { s, sgd })

然后删除条件&& o.sgd.intStoreGroup==intStoreGroup

但您必须使用EF / Linq-to-SQL

进行测试

关于为什么......我不确切知道为什么,但我可以告诉你:

 SELECT * FROM A LEFT JOIN B ON something WHERE B.Something = C

相当于

 SELECT * FROM A INNER JOIN B ON something WHERE B.Something = C

因为WHERE B.Something = C强烈暗示B.Something IS NOT NULL,这强烈暗示B已经被发现&#34;。因此,如果B没有找到&#34;那么WHERE&#34;就会失败&#34;并且不能返回该行。与INNER JOIN一样。