Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Left join with OrderBy in LINQ

I have two lists. First one is a list of Tasks pulled from an API (APITasks), the second one is a list Task that I have on my local SQL DB. The tool allows users to "claim" an APITask and record that claim locally by storing the TaskIssueId.

It can happen that from time to time an APITask gets removed. My tool has code that will notice that and mention it to the user when they list all their "claimed" task. Now the problem I'm having is getting the user's tasks to be sorted through the APITasks (sorted by AnotherInternalId which is another Id, complicated and not relevant) and if any task is not available anymore still have it displayed (with my code catching the exception and displaying a message).

Here's my sql query:

myTasks = (from m in myTasksFiltered
           join d in APITasks on m.TaskIssueId equals d.TaskIssueId
               into joinedData
           from d in joinedData.DefaultIfEmpty()
           let index = (int?)d.AnotherInternalId  ?? 0
           orderby index
           select m).ToList();

This thread helped create that query but I keep getting a null reference exception error because when the query reaches the local task that is not present in the APITask, d becomes null and everything blows up from there.

like image 521
LanFeusT Avatar asked Feb 22 '23 06:02

LanFeusT


2 Answers

You need check that d is not null, not AnotherInternalId

myTasks = (from m in myTasksFiltered
           join d in APITasks on m.TaskIssueId equals d.TaskIssueId
               into joinedData
           from d in joinedData.DefaultIfEmpty()
           let index = d == null ? 0 : d.AnotherInternalId
           orderby index
           select m).ToList();
like image 170
cadrell0 Avatar answered Mar 05 '23 19:03

cadrell0


myTasks = (from m in myTasksFiltered
       join d in APITasks on m.TaskIssueId equals d.TaskIssueId
           into joinedData
       from d in joinedData.DefaultIfEmpty()
       where d != null
       let index = (int?)d.AnotherInternalId  ?? 0
       orderby index
       select m).ToList();
like image 34
Harps Avatar answered Mar 05 '23 19:03

Harps