我想将以下sql查询转换为Linq: -
exec('SELECT * FROM (SELECT MAS.EmployeeId, MAS.ENTRY_DATE, IT.InDate
IN_DATE, OT.InDate OUT_DATE, MAS.SHIFT_CODE, MAS.SHIFT_FLAG, CASE WHEN
(IT.InDate IS NOT NULL) AND (OT.INDATE IS NOT NULL) THEN CASE WHEN IT.InDate = OT.InDate THEN ''FALSE'' ELSE ''OK'' END ELSE ''FAIL'' END AS VALID FROM (SELECT EmployeeId, Time_Date1 ENTRY_DATE,Time_Field1 SHIFT_CODE, Time_Field2
SHIFT_FLAG FROM [WWEGG8f9bf41c16].[TO_TempInOutNew] GROUP BY EmployeeId, Time_Date1, Time_Field1, Time_Field2) MAS LEFT JOIN [WWEGG8f9bf41c16].[TO_TempInOutNew] IT ON IT.EmployeeId=MAS.EmployeeId AND
IT.Time_Date1=MAS.ENTRY_DATE AND IT.InOutFlag=''I'' LEFT JOIN [WWEGG8f9bf41c16].[TO_TempInOutNew] OT ON OT.EmployeeId=MAS.EmployeeId AND OT.Time_Date1=MAS.ENTRY_DATE AND OT.InOutFlag=''O'') MY_IN_OUT')
所以我在Linqer的帮助下做到了这一点: -
var qry = (from MY_IN_OUT in
(
(from MAS in
(
(from TO_TempInOutNew in listTempInOutNew
group TO_TempInOutNew by new
{
TO_TempInOutNew.EmployeeId,
TO_TempInOutNew.Time_Date1,
TO_TempInOutNew.Time_Field1,
TO_TempInOutNew.Time_Field2
} into g
select new
{
g.Key.EmployeeId,
ENTRY_DATE = g.Key.Time_Date1,
SHIFT_CODE = g.Key.Time_Field1,
SHIFT_FLAG = g.Key.Time_Field2
}))
join IT in listTempInOutNew
on new { EmployeeId = Convert.ToInt32(MAS.EmployeeId), Time_Date1 = Convert.ToDateTime(MAS.ENTRY_DATE), InOutFlag = "I" }
equals new { IT.EmployeeId, IT.Time_Date1, IT.InOutFlag } into IT_join
from IT in IT_join.DefaultIfEmpty()
join OT in listTempInOutNew
on new { EmployeeId = Convert.ToInt32(MAS.EmployeeId), Time_Date1 = Convert.ToDateTime(MAS.ENTRY_DATE), InOutFlag = "O" }
equals new { OT.EmployeeId, OT.Time_Date1, OT.InOutFlag } into OT_join
from OT in OT_join.DefaultIfEmpty()
select new
{
EmployeeId = (int?)MAS.EmployeeId,
ENTRY_DATE = (DateTime?)MAS.ENTRY_DATE,
IN_DATE = (DateTime?)IT.InDate,
OUT_DATE = (DateTime?)OT.InDate,
MAS.SHIFT_CODE,
MAS.SHIFT_FLAG,
VALID =
IT.InDate != null &&
OT.InDate != null ? (
IT.InDate == OT.InDate ? "FALSE" : "OK") : "FAIL"
}))
select new
{
MY_IN_OUT.EmployeeId,
MY_IN_OUT.ENTRY_DATE,
MY_IN_OUT.IN_DATE,
MY_IN_OUT.OUT_DATE,
MY_IN_OUT.SHIFT_CODE,
MY_IN_OUT.SHIFT_FLAG,
MY_IN_OUT.VALID
}).ToList();
它在位置OUT_DATE = (DateTime?)OT.InDate,
给出了错误。
OT.InDate显示为null。不应该是这种情况。
对象引用未设置为对象的实例。
有关如何解决此问题的任何建议?
答案 0 :(得分:1)
您正在使用左连接,因此对象IT和OT可能为空。 替换选择部分如下。
select new
{
EmployeeId = (int?)MAS.EmployeeId,
ENTRY_DATE = (DateTime?)MAS.ENTRY_DATE,
IN_DATE = (DateTime?)IT != null ? IT.InDate : null,
OUT_DATE = (DateTime?)OT != null ? OT.InDate : null,
MAS.SHIFT_CODE,
MAS.SHIFT_FLAG,
VALID =
IT != null && IT.InDate != null &&
OT != null && OT.InDate != null ? (
IT.InDate == OT.InDate ? "FALSE" : "OK") : "FAIL"
}))