1

你知道如何将这个 SQL 查询写到 linq 吗?

SELECT * 
FROM 
  a 

  INNER JOIN b 
  ON a.FkSubmissionId = b.Id 

  RIGHT JOIN c 
  ON a.FkItemId = c.Id 

WHERE 
 (b.FkUserId = '...' OR b.FkUserId is null) 
 and 
 (c.FkTenderId = 2)

我使用 Linquer,我从该工具中获得的最好的东西是:

林克:

from 
  items in _context.Items 

from 
  si in _context.si

  join s in _context.s 
  on new { fki = si.fki } equals new { fki = s.Id } 

into 
  submissions_join

from 
  s in submissions_join.DefaultIfEmpty()

...

结果在 SQL :

SELECT * 
FROM 
  [Items] AS [t0]

  CROSS JOIN [SubmissionsItems] AS [t1]

  LEFT OUTER JOIN [Submissions] AS [t2] 
  ON [t1].[FkSubmissionId] = [t2].[Id]

WHERE 
  (([t2].[FkUserId] = @p0) OR (([t2].[FkUserId]) IS NULL)) 
  AND 
  ([t0].[FkTenderId] = @p1)

所以最终结果不是我从我需要的查询中得到的......

感谢您的帮助 !!!

4

2 回答 2

1

试试这个:

var part1 =
    from x in a
    join y in b on x.FkSubmissionId equals y.Id
    where b.FkUserId = "..."
    select new {x, y};

var part2 =
    from c in z
    where c.FkTenderId == 2
    join xy in part1
        on z.Id equals xy.x.FkItemId
        into xys
    from xy in xys.DefaultIfEmpty()
    select new {xy.x, xy.y, z};
于 2012-09-17T13:44:37.973 回答
0

我会重新排序您的查询,以便您可以使用左连接而不是右连接

var query = from c in context.C
            from a in context.A.Where(x => c.Id == x.FkItemId)
                               .DefaultIfEmpty()
            join b in context.B on a.FkSubmissionId equals b.id
            where b.FkUserId == '...' || b.FkUserId == null
            where c.FkTenderId == 2
            select new {
              a,
              b,
              c
            };
于 2012-09-17T14:03:21.147 回答