试图将PIVOT SQL转换为LINQ lambda exp

时间:2017-06-12 12:50:56

标签: c# sql-server linq lambda

您好我试图转换此SQL

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

到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");
                }

它不起作用,我不知道为什么。请帮助。

1 个答案:

答案 0 :(得分: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"); 
}

this goes to the DB and get the incidents where ClientProductVehicleId equals to the one received and returns the last incident. and take the last incident to get their incident states. if the incident state is not the last one (3) throw the exception.