具有多个条件和in子句的C#EF Linq语法查询

时间:2019-03-06 16:17:30

标签: c# sql entity-framework linq

我在实体框架上有一个带有查询语法的linq。 这是sql

Select * from x
join y on y.a = x.a
join p on p.b = x.b and x.n in (3,4)
--other joins

这是门廊

var k = from typeX in x
join typeY in y on y.a equals x.a
join typeP in p on p.b = x.b  ???? (AND x.n in 3,4???)
//Other joins

这些无效

join p in p on x.b equals p.b and x.n.Contains(3,4)

即使 || && 都不起作用,也不会被识别为关键字

也不能使用括号(带有||或and,并在内部)。

我想念什么?

我需要加入多个条件,其中一个条件是“ IN CLAUSE”。

谢谢

2 个答案:

答案 0 :(得分:0)

Here is a DotNetFiddle并提供了一个有效的示例,说明了我对您的问题的看法:

您可以将||放入一个数组并将其添加到LINQ查询中,然后检查该数组是否包含3,4

x.n

int[] myNumbers = new int[] {3, 4};

这是完整的查询(变量与您的略有不同,因此我更容易阅读它们,但逻辑应该相同):

join p in pData on x.b equals p.b where myNumbers.Contains(x.n)

答案 1 :(得分:0)

我对LINQ的查询语法不是很熟悉,因此我将展示如何使用方法语法。

您想要联接多个表,并且在进行一些联接之后,您想与表P联接。但是,您不想将所有先前的联接结果与表P联接,您只想使用那些先前的联接结果xn等于3或4。

如果您将x.N值都不为3或4的所有先前联接结果丢弃,那么将它们放在先前联接结果中是没有用的:

var requiredNvalues = new int[] {3, 4};
var result = X
    .Where(x => requiredNvalues.Contains(x.N)  // keep only the required x elements

    // Join the remaining elements of X with Y:
    .Join(Y,                   
    x => x.A,      // from every x in X take the A
    y => y.A,      // from every y in Y take y.A

    // ResultSelector: when they match make one new object containing matching X and Y
    (x, y) => new  {X=x, Y=y})

   // join  with third table:
   .Join(Z,

   previousJoinResult => previousJoinResult.X.Id,
                            // from every item in previous join result take X.Id
   z => z.xId,              // from every z from Zcollection take Xid,

   // ResultSelector: when they match make one new object containing matching X Y Z
   (previousJoinResult, z) => new {X = previousJoinResult.X, Y = previousJoinResult.Y, Z = z}
   ... etc, other joins

以类似的方式加入连续,直到您想加入P:

   .Join(P,
   previousJoinResult => previousJoinResult.X.b, 
                             // from every X from the previous join result take b
   p => p.b                  // from every p take b

   // resultSelector: select X Y Z ... P
   (previousJoinResult, p) => new
   {
       X = previousJoinResult.X,
       Y = previousJoinResult.Y,
       Z = previousJoinResult.Z,
       ...
       P = p;
   });

简单的漫画卓悦!