c# - Linq 加入表中的最后一个实例

标签 c# sql-server linq join

我有一个包含流程所有步骤的工作流表。让我们处理其中两种状态:

  1. 已保存(新项目已保存但尚未提交)
  2. 已提交(已提交供审核的项目)

现在我想创建一个 BatchSumbit 函数来提交所有未提交的项目。为此,我需要查询所有最新工作流状态为“已保存”的项目。该项目的所有历史工作流程条目仍然存在,并且它可以从“已提交”返回“已保存”几次。

表结构如下:

enter image description here

现在我想要一个 linq 查询来满足我的要求:

from wasteInformation in wasteDB.WasteInformations
join workFlowHistory in wasteDB.WorkFlowHistories on wasteInformation.WasteInformationId equals workFlowHistory.WasteInformationId
// Join with last instance in workflow table (where workflowHistory.DateAdded is greatest)
where workFlowHistory.WorkFlowStep == "Saved"
      && wasteInformation.WasteProgrammeId == captureModel.WasteProgrammeId
      && wasteInformation.WasteSourceId == captureModel.WasteSourceId
select new
{
    WasteInformationId = wasteInformation.WasteInformationId,
    FinancialQuarter = wasteInformation.FinancialQuarter,
    FinancialYear = wasteInformation.FinancialYear,
    WasteProgrammeId = wasteInformation.WasteProgrammeId,
    WasteMonth = wasteInformation.WasteMonth,
    WasteYear = wasteInformation.WasteYear,
    DateCaptured = wasteInformation.DateCaptured,
    WasteSourceId = wasteInformation.WasteSourceId,
    WasteDate = wasteInformation.WasteDate
}

查询将给出该项目的所有已保存条目。如果该项目的最后一个条目的 WorkFlowStep 为“已保存”,我希望它给我该项目


编辑: 我有一些看起来有用的东西。还需要再测试一下:

var SavedWasteInformation = wasteDB.WasteInformations.Where(wi => wi.WorkFlowHistories.FirstOrDefault(wf => wf.DateAdded == wi.WorkFlowHistories.Max(wf_in => wf_in.DateAdded)).WorkFlowStep == "Saved"
                            && wi.WasteProgrammeId == captureModel.WasteProgrammeId
                            && wi.WasteSourceId == captureModel.WasteSourceId);

编辑: 我上面的解决方案和下面 Vladimirs 的解决方案似乎都有效,但在检查执行计划后,Vladimirs 的解决方案看起来是更好的选择:

enter image description here

最佳答案

假设您在 WasteInformation 上收集了 WorkFlowHistories 我相信查询会选择 WasteInformations 及其最新的 WorkFlowHistory(如果有的话):

from wasteInformation in wasteDB.WasteInformations
where wasteInformation.WasteProgrammeId == captureModel.WasteProgrammeId
      && wasteInformation.WasteSourceId == captureModel.WasteSourceId
select new
{
    WasteInformation = wasteInformation,
    LastSavedWorkFlowHistory = wasteInformation.WorkFlowHistories
        .Where(x => x.WorkFlowStep == "Saved")
        .OrderByDescending(x => x.DateAdded)
        .FirstOrDefalt()
}

关于c# - Linq 加入表中的最后一个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27124236/

相关文章:

c# - 框架 'Microsoft.NETCore.App' ,版本 '5.0.13' 未找到

javascript - SQL 一次搜索多个 id - Node/Express

c# - 在 T-SQL 中返回重复行

sql-server - FluentNHibernate - 设置数据库列的默认值(SQL Server)

c# - 使用linq检查树的长度

c# - IEnumerable<T> 与数组

C# Linq 按键组合多个序列

c# - 对列表进行分组 - 寻找更好的方法

c# - Max()函数的测试用例设计

c# - 支持密码 rsa 私钥的 SSH 库