我正在尝试将SQL查询转换为LINQ to实体查询,但是LINQ select 块遇到了一些问题。
以下是按预期执行的SQL查询:
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
到目前为止,这是LINQ to实体查询:
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();
LINQ查询在以下两行中的任何一行上失败,这两行尝试分配从左外连接结果中检索的值。如果省略以下行,则LINQ查询完成且没有错误:
Status = fork.Status,
MapID = map.ID
为什么这两个属性赋值在LINQ查询的select块中失败?
答案 0 :(得分:1)
问题在于,由于您的外部联接,fork
和map
可能为空。当然,当它们为空时,您无法访问其属性。你可能需要这样的东西:
Status = (fork == null) ? null : fork.Status,
MapID = (map == null) ? null : map.ID