如何在linq中查询

时间:2010-09-24 23:24:48

标签: linq linq-to-entities

我有这个SQL

SELECT *
FROM  [dbo].[LeftHand]
        left outer JOIN [dbo].[Head]  ON [LeftHand].[ID] = [Head].[LeftHand_Id]
        WHERE [Head].[RightHand_Id] Not IN (59,60,63,64,65) or [Head].[RightHand_Id] is null 

        [Head]
        */  \*
        /    \
      1/      \1
[LeftHand]  [RightHand]       ([LeftHand may have more than one [RightHand]  )

如你所见,我想获得所有[LeftHand]对象(包括那些没有任何[RightHand]的对象),但是如果他们有[RightHand],那么它的ID必须来自这个列表( 59,60,63,64,65)

那么如何才能在LINQ中获得相同的结果?

LINQ to Entities,
框架4

感谢

2 个答案:

答案 0 :(得分:0)

您能否为我澄清一点,但在您的问题中,您声明该ID必须来自清单

  

但如果他们有[RightHand],那么它的ID必须来自此列表(59,60,63,64,65)

但你的SQL却恰恰相反;它排除了列表中的ID

  

WHERE [Head]。[RightHand_Id] Not IN(59,60,63,64,65)

是否要包含列表中的ID或将其排除?


假设您确实要排除它们;这应该适合你。

using (var context = new ContextName())
{
    //here are the ids we want to filter by
    var ids = new List<int> { 59,60,63,64,65 };
    //get all left hands without a matching right hand
    var result = context.LeftHands.Where(l => l.Head.RightHand_Id == null
                                           //or right hands that aren't in the list
                                           || !ids.Contains(l.Head.RightHand_Id));
}

如果你想要包含它们;改变这部分代码...

//or right hands that aren't in the list
|| !ids.Contains(l.Head.RightHand_Id));

看起来像这样......

//or right hands that are in the list
|| ids.Contains(l.Head.RightHand_Id));

答案 1 :(得分:0)

我解决了它

以防任何人需要答案

using (var context = new ContextName())
{
    var ids = new List<int> { 59,60,63,64,65 };
    var result =
        from l in context.LeftHand
        join Head in contaxt.Head on l equals Head.LeftHand into ljh
        from j1 in ljh.DefaultIfEmpty()
        where !ids.Contains(j1.RightHand.ID) || j1 == null
        select l;
}

谢谢你DoctaJonez你的回答帮助我达到了目的。