我正在尝试将以下SQL查询转换为LINQ,但我得到了一个“对象引用未设置为对象实例”的错误。
SQL查询
SELECT a.ID_TARGET,a.TARGET_NAME, b.OBJECTIVE_NAME, c.PERSPECTIVE_NAME FROM IL_OPR_MTR_TGT AS a
LEFT JOIN IL_OPR_MTR_OBJ b ON a.TARGET_OBJECTIVE_ID = b.ID_OBJECTIVE
LEFT JOIN IL_OPR_MTR_PRSPCT c ON b.OBJECTIVE_PERSPECT_ID = c.PERSPECTIVE_ID;
SQL输出
ID_TARGET |TARGET_NAME |OBJECTIVE_NAME |PERSPECTIVE_NAME
----------|-------------|---------------|----------------
7 |TGT_01 | TST02 |PERSPECTIVE_01
8 |TGT01 | TST02 |PERSPECTIVE_01
9 |TARGET_02 | TST02 |PERSPECTIVE_01
10 |TARGET003AA | (null) |(null)
LINQ查询
var data = (from a in allTargets
join b in allObjectives on a.TARGET_OBJECTIVE_ID equals b.ID_OBJECTIVE into partial1
from b in partial1.DefaultIfEmpty()
join c in allPerspectives on b.OBJECTIVE_PERSPECT_ID equals c.PERSPECTIVE_ID into partial2
from c in partial2.DefaultIfEmpty()
select new
{
ID_TARGET = a.ID_TARGET,
TARGET_NAME = a.TARGET_NAME,
OBJECTIVE_NAME = b != null ? b.OBJECTIVE_NAME : "",
PERSPECTIVE_NAME = c != null ? c.PERSPECTIVE_NAME : ""
}).ToList();
我猜问题出在这里,因为我尝试连接两个NULL值,但我想不出如何解决...
join c in allPerspectives on b.OBJECTIVE_PERSPECT_ID equals c.PERSPECTIVE_ID into partial2
from c in partial2.DefaultIfEmpty()
allTargets
是什么?从异常来看,似乎是某种内存收集?如果它是IQueryable
(LINQ到实体),那么你的查询不会有任何问题。 - Ivan Stoev