我試圖將下面的SQL查詢翻譯成LINQ,但我得到了「未設置爲對象實例的對象引用」。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 OUTPUT
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()
我認爲它是你引用數據的「a」和「b」名稱,而你的所有數據都在最後一個partial2 Enumerable集合中,所以你應該引用它們由「c」別名的你的物品收集的名稱.. –
什麼是'allTargets'?看着這個異常,似乎是一些內存集合?如果它是'IQueryable'(LINQ to Entities),那麼您的查詢將無法解決任何問題。 –