2017-06-12 60 views
0

您好我想試圖PIVOT SQL轉換成LINQ拉姆達EXP

select * 
from Incidents i join 
(select IncidentId, IncidentStatusId, DateCreated from IncidentStates) src 
     pivot 
     (
     max(DateCreated) for IncidentStatusId in ([1],[2],[3]) 
     ) Inc 
     on Inc.IncidentId = i.IncidentId 
     where Inc.[3] is null 

轉換這個SQL到lambda表達式,所以經過多次嘗試我結束了這個

var vehicleIncident = _moiFleetContext.Incidents.Where(i => i.ClientProductVehicleId == clientProductVehicleId).LastOrDefault(); 

       var incident = _moiFleetContext.IncidentStates.Where(i => i.IncidentId == vehicleIncident.IncidentId) 
        .GroupBy(i => i.IncidentId) 
        .Select(st => new 
        { 
         id = st.Key, 
         status = st.Where(sta => sta.IncidentStatusId == 1).Select(s => s.DateCreated), 
         status2 = st.Where(sta => sta.IncidentStatusId == 2).Select(s => s.DateCreated), 
         statu3 = st.Where(sta => sta.IncidentStatusId == 3).Select(s => s.DateCreated) 

        }).ToList(); 
       if (incident.Where(i => i.statu3 == null) != null) 
       { 
        throw new MoiFleetException("Please work"); 
       } 

它確實不工作,我不知道爲什麼,請幫忙。

+0

*什麼,*特別是,不能正常工作?你有錯誤嗎?你拋出異常嗎?數據不具有相同的回報/結果嗎? – gravity

+0

它不會拋出異常。 –

+0

請將[問題]出現在問題中,並提供任何錯誤或調試問題的可視性。 – gravity

回答

0
var vehicleIncident = _moiFleetContext.Incidents.Where(i => i.ClientProductVehicleId == clientProductVehicleId).ToList().LastOrDefault(); 

var vehicleIncidentState = _moiFleetContext.IncidentStates.Where(i => i.IncidentId == vehicleIncident.IncidentId).ToList().LastOrDefault(); 

if (vehicleIncidentState.IncidentStatusId != 3) 
{ 
throw new MoiFleetException("Please work"); 
} 

這會轉到數據庫並獲取ClientProductVehicleId等於收到的事件並返回最後事件的事件。 並採取最後一次事件來獲得他們的事件狀態。如果事件狀態不是最後一個(3)拋出異常。