我正在尝试将以下SQL查询转换为LINQ,但我得到一个“对象引用未设置为对象的实例。”
SQL QUERY
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 QUERY
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()
答案 0 :(得分:1)
您必须在查询中对b
进行空值检查,例如:
join c in allPerspectives on (b == null ? "no-value" : b.OBJECTIVE_PERSPECT_ID) equals c.PERSPECTIVE_ID
答案 1 :(得分:1)
您还可以尝试实例化新对象,而不是使用default
null
。语法类似于partial1.DefaultIfEmpty(new AllObjective())