2012-09-21 40 views
0

我對Linq比較陌生,現在我遇到了以下問題。 我有以下功能:在LINQ to SQL中與GROUP BY左連接

public Dictionary<DateTime, List<PloegenRooster_Uitzonderingen>> GetPloegenRoosterUitzonderingen(char ploeg, DateTime fromDate, DateTime toDate) 
    { 
     return (
      from item in this.GetTable<PloegenRooster_Uitzonderingen>() 
      join itemType in PloegenRooster_Uitzondering_Types on item.UitzonderingTypeId equals itemType.Id 
      group item by item.Datum 
     ).ToDictionary(d => d.Key, d => d.ToList()); 
    } 

這很好用。但是,現在我正在試圖將其變爲左連接。 我結束了以下內容:

public Dictionary<DateTime, List<PloegenRooster_Uitzonderingen>> GetPloegenRoosterUitzonderingen(char ploeg, DateTime fromDate, DateTime toDate) 
    { 
     return (
      from item in this.GetTable<PloegenRooster_Uitzonderingen>() 
      join itemType in PloegenRooster_Uitzondering_Types on item.UitzonderingTypeId equals itemType.Id into itemTypeJ 
      from itemTypeS in itemTypeJ.DefaultIfEmpty() 
      group item by item.Datum 
     ).ToDictionary(d => d.Key, d => d.ToList()); 
    } 

但現在我收到以下異常:

The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type. 

回答

0

在(內蒙古)加入像在第一個例子只匹配行的行在另一個表中被選中。

在左連接從表A中選擇所有行。如果第二個表中沒有適合連接的行,則第二個表的列將填充NULL值。創建的對象具有整型屬性。整型屬性不包括NULL值。

您必須將整數屬性更改爲可以爲null的數據類型或使整數屬性可以爲空。

+0

謝謝。這對我來說有點愚蠢。在我更改數據庫列以允許空值後,我忘記更新DataContext。 – sroes

0

在您的第一次嘗試中有一個equi-join,並且連接中的兩個表都有結果。但是,在使用左連接時,由於兩個表之間沒有匹配鍵,所以表中的一個表的結果爲空值。

如前所述通過@TheJoelaut要麼使你的屬性可爲空或通過添加一個SELECT子句指定在空的情況下,零或有效整數數據:

選擇itemTypeS == NULL? (Int32)0.00:itemTypeS.property