2012-09-21 41 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