LINQ to Entities - Multiple Unions - Null Reference Exception in 'Select'

I am trying to convert a SQL query to a LINQ query on objects, but I have some problems with the LINQ select block .

Here is the SQL query that executes as expected:

SELECT distinct( p.PendingID,
        p.Description,
        p.Date,
        f.Status,
        u.UserName,
        m.MapID
    FROM    Pending p
    JOIN    Users u 
   ON p.UserID = u.UserID
    LEFT JOIN Forks f 
   ON p.PendingID = f.PendingID
    LEFT JOIN Maps m
      ON f.ForkID = m.ForkID
    ORDER BY p.Date DESC

The following is a LINQ query for objects:

var pList = (from pending in pendingItems
// JOIN
from user in userList.Where(u => pending.UserID == u.UserID)
// LEFT OUTER JOIN
from fork in forkList.Where(f => pending.ID == f.PendingID)
.DefaultIfEmpty()
// LEFT OUTER JOIN
from map in mapList.Where(m => fork.ID == m.ForkID)
.DefaultIfEmpty()
orderby pending.Date descending
select new
{
 ItemID = pending.ID,                 // Guid
 Description = pending.Description,   // String
 Date = pending.Date,                 // DateTime
 Status = fork.Status,               // Int32 (*ERROR HERE*)
 UserName = user.UserName,            // String 
 MapID = map.ID                       // Guid (*ERROR HERE*)
})
.Distinct()
.ToList();

The LINQ query fails on any of the following two lines that try to assign values โ€‹โ€‹obtained from the results of the left external join . If the following lines are omitted, the LINQ query completes without errors:

Status = fork.Status,
MapID = map.ID

Why are these 2 property assignments not executed in the LINQ query select block?

+3
source share
1 answer

, - fork map . , , . - :

Status = (fork == null) ? null : fork.Status,
MapID = (map == null) ? null : map.ID 
+1

Source: https://habr.com/ru/post/1781499/


All Articles