简体   繁体   English

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

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

I'm rather new to Linq, now i have the following problem. 我对Linq相当陌生,现在我遇到以下问题。 I have the following function: 我有以下功能:

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

This works perfectly. 这很完美。 However, now I'm trying to turn this into a LEFT JOIN. 但是,现在我正在尝试将其变为LEFT JOIN。 I ended up with the following: 我得出以下结论:

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

But now I'm getting the following exception: 但是现在我得到以下异常:

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

In a (Inner)Join like in the first example only the rows that match a row in the other table are selected. 在第一个示例中的(内部)联接中,仅选择与另一个表中的一行匹配的行。

In the Left Join all rows from Table A are selected. 在左联接中,选择表A中的所有行。 If there are no rows in the second table that fit the join the columns for the second table are filled with NULL values. 如果第二个表中没有适合联接的行,则第二个表的列将填充NULL值。 The Objects that are created are having a Integer Property. 创建的对象具有整数属性。 Integer Properties don't except NULL Values. 整型属性不包括NULL值。

You either have to change the Integer Property to a nullable datatype or make the Integer Property nullable. 您必须将Integer属性更改为可为空的数据类型,或者使Integer属性为可为空。

In your first attempt there is a equi-join and both tables in the join have a result. 在您的第一次尝试中,存在一个等值联接,并且联接中的两个表都有结果。 However when using the left join, one of your tables is resulting in null values as there is no matching key between both tables. 但是,当使用左联接时,由于两个表之间没有匹配键,因此其中一个表将导致空值。

As mentioned by @TheJoelaut either make your properties nullable or assign zeroes or valid integer data in case of null by adding a select clause : 正如@TheJoelaut所提到的,通过添加select子句,可以使您的属性为空,或者为零或有效的整数数据(如果为null):

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

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

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