LINQ左右连接查询

时间:2016-06-12 03:07:49

标签: c# sql-server linq

这是我的SQL查询,如何在LINQ中生成此查询:

SELECT 
    TimeTable.StartTime,
    sum(Booking.Quantity) as Total
FROM PromotionSlot
RIGHT JOIN TimeTable
ON PromotionSlot.StartHour = TimeTable.StartTime
LEFT JOIN Booking
ON PromotionSlot.ID = Booking.PromotionSlotID
GROUP BY TimeTable.StartTime

结果:

|StartTime    |Total|
---------------------
 9             NULL
 10            NULL
 11            2
 12            2
 13            NULL
 14            NULL
 15            NULL
 16            NULL
 17            NULL
 18            NULL
 19            NULL
 20            NULL
 21            NULL

这就是我的尝试,我不确定linq的结构在我的SQL查询中是否正确。但我遇到有关The cast to value type 'Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.的错误请指导我,提前谢谢大家!

var bookingdata = 
    (from ps in dc.PromotionSlots
     join t in dc.TimeTables on ps.StartHour equals t.StartTime into Ts
     join bo in dc.Bookings on ps.ID equals bo.PromotionSlotID into Bs
     from time in Ts.DefaultIfEmpty()                         
     from book in Bs.DefaultIfEmpty()
     group new {time,book} by time.StartTime into NewGroup
     select new dataView
     {
         StartTime = NewGroup.Key,
         numBookings = NewGroup.Select(a => a.book!=null? a.book.Quantity: 0).Sum()
     }).ToList();

这是我的dataView型号

public class dataView
{
    public int? StartTime { get; set; }
    public int? numBookings { get; set; }
}

更新:

将我的dataView模型中的StartTime更改为int?,这是使用console.log()

的结果
Format: @:console.log("* " + "@item.StartTime" + ":" + "@item.numBookings");
* :0
* 10:0
* 11:2
* 12:2

我找到了上述console.log()出现此结果的原因。我尝试将SQL查询RIGHT JOIN TimeTable更改为LEFT JOIN TimeTable。返回结果与我的LINQ输出完全相同。

1 个答案:

答案 0 :(得分:2)

我认为您遇到的问题是,在即席查询结果中,任何列值都可以为null(例如,结果示例中的Total列具有混合值,int和null)。但是C#不是那么宽松,一个空值不能填入整数值。

我认为在dataView类型中,numBookings属性可能设置为int,而C#中的int类型不可为空。

我相信如果你把它改成一个可以为空的int,比如:

public int? numBookings { get; set; }

那么这可能会修复你的错误。如果不是这样,那么以下可能工作:

numBookings = NewGroup.Select(a => a.book!=null ? (a.book.Quantity ?? 0): 0).Sum() ?? 0

但我不确定最后一个。

<强>更新

如果更新LINQ查询以对两个连接使用LEFT JOIN,如下所示:

var bookingdata = (
    from t in dc.TimeTables 
    join ps in dc.PromotionSlots on t.StartTime equals ps.StartHour into Ts
    from time in Ts.DefaultIfEmpty()
    join bo in dc.Bookings on time.ID equals bo.PromotionSlotID into Bs
    from book in Bs.DefaultIfEmpty()
    group new {time, book} by time.StartTime into NewGroup
    select new dataView
    {
        StartTime = NewGroup.Key,
        numBookings = NewGroup.Select(a => a.book!=null? a.book.Quantity: 0).Sum()
    }
).ToList();

这是否使结果与SQL查询更加一致?