将SQL Left Join转换为Linq

时间:2012-03-08 04:43:42

标签: .net sql linq

我在将这个SQL语句转换为LINQ时遇到了一些困难:

Declare @ind date, @outd date
set @ind = '2012-03-17'
set @outd = '2012-03-18'

SELECT k.id
FROM Kennels k
LEFT JOIN (SELECT * 
            FROM Reservations 
            WHERE (DateIn >= @ind and DateIn < @outd) or  (DateOut > @ind and DateOut <= @outd)) r ON k.id = r.Kennel_ID
WHERE r.kennel_id is null

的LINQ:

Dim available = From k In Kennels _
                    Group Join r In db.Reservations.Where(Function(fx) (fx.DateIn >= Date_From And fx.DateIn < Date_To) Or (fx.DateOut > Date_From And fx.DateOut <= Date_To)) On k Equals r.Kennel Into Group _
                    From r In Group.DefaultIfEmpty
                    Where r.Kennel.ID Is Nothing
                    Select k

我的Linq语句的问题是当r什么都没有时,查询的“where r.Kennel.ID”部分会失效。

我很感激帮助重写此查询!

谢谢,

汤姆

1 个答案:

答案 0 :(得分:1)

您可以将Where r.Kennel.ID Is Nothing更改为Where r Is Nothing

但是在c#中我会写

var available =
    from k in db.Kennels
    where !k.Reservations.Any(r => r.DateIn >= Date_From && r.DateIn < Date_To) || (r.DateOut > Date_From && r.DateOut <= Date_To)
    select k;

因为我觉得它更容易阅读 抱歉我的VB有点生疏,但我认为你可以轻松翻译它(||Or&&And!是{{ 1}})