【问题标题】:Trying to convert PIVOT SQL into LINQ lambda exp试图将 PIVOT SQL 转换为 LINQ lambda exp
【发布时间】:2017-06-12 12:50:56
【问题描述】:

您好,我正在尝试转换此 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");
                }

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

【问题讨论】:

  • 具体是什么不能正常工作?你有错误吗?你抛出异常吗?数据是否没有等效的回报/结果?
  • 它不会抛出那个异常。
  • edit 解决您的问题,并提供您对问题的任何错误或调试可见性。
  • 谢谢哥们,但它有效。欢呼
  • @gravity 我使用这个简单的代码来获得解决方案。 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("请工作"); }

标签: c# sql-server linq lambda


【解决方案1】:
 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),则抛出异常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-01
    • 2018-09-23
    相关资源
    最近更新 更多