SQL到Linq转换左外连接

时间:2012-09-28 17:40:44

标签: sql linq-to-sql

我正在尝试将此SQL语句转换为LINQ

SELECT     
  a.UserId, b.Date, a.Value1
FROM         
  web.Table2 AS b
LEFT OUTER JOIN
  web.Table1 AS a 
ON 
  b.Date = a.CreateDate AND UserId = 1

这就是我的工作:

Dim query = From a In ctx.Table1 _
        Group Join b In ctx.Table2 On b.Date Equals a.CreateDate Into group1 = Group
        From x In group1.DefaultIfEmpty() _
        Where ls.UserId = 1 _
        Select a.UserId, x.Date, a.Value1

2 个答案:

答案 0 :(得分:1)

您的代码应该是(检查别名b,您使用的是x)

Dim query = From a In ctx.Table1 _
        Join b In ctx.Table2 _ 
        On b.Date Equals a.CreateDate Into group1 = Group _
        Where a.UserId = 1 _
        From b In group1.DefaultIfEmpty() _            
        Select a.UserId, b.Date, a.Value1

答案 1 :(得分:0)

您总是可以直接在LINQ To SQL中执行查询,例如:

IEnumerable<MyClass> results = db.ExecuteQuery<MyClass>(@"
    SELECT a.UserId, b.Date, a.Value1 
    FROM web.Table2 AS b 
    LEFT OUTER JOIN web.Table1 AS a ON b.Date = a.CreateDate 
        AND UserId = 1");