简体   繁体   中英

LEFT JOIN with GROUP BY in LINQ to SQL

I'm rather new to Linq, now i have the following problem. 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. 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. If there are no rows in the second table that fit the join the columns for the second table are filled with NULL values. The Objects that are created are having a Integer Property. Integer Properties don't except NULL Values.

You either have to change the Integer Property to a nullable datatype or make the Integer Property nullable.

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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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