繁体   English   中英

在LINQ to SQL中通过GROUP BY左联接

[英]LEFT JOIN with GROUP BY in LINQ to SQL

我对Linq相当陌生,现在我遇到以下问题。 我有以下功能:

    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());
    }

这很完美。 但是,现在我正在尝试将其变为LEFT JOIN。 我得出以下结论:

    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. 

在第一个示例中的(内部)联接中,仅选择与另一个表中的一行匹配的行。

在左联接中,选择表A中的所有行。 如果第二个表中没有适合联接的行,则第二个表的列将填充NULL值。 创建的对象具有整数属性。 整型属性不包括NULL值。

您必须将Integer属性更改为可为空的数据类型,或者使Integer属性为可为空。

在您的第一次尝试中,存在一个等值联接,并且联接中的两个表都有结果。 但是,当使用左联接时,由于两个表之间没有匹配键,因此其中一个表将导致空值。

正如@TheJoelaut所提到的,通过添加select子句,可以使您的属性为空,或者为零或有效的整数数据(如果为null):

选择itemTypeS == null吗? (Int32)0.00:itemTypeS.property

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM