You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过LINQ高效获取特定患者的最新录入子计划

高效检索特定患者最新子计划的解决方案

嘿,我来帮你搞定这个问题!针对你提到的需求——从Patient关联的Plan实体中,高效获取特定患者的所有最新录入的子计划(PlanDetail类型的子项,可能为null),我分两种常见场景给你具体的实现方案,以下示例基于EF Core(毕竟你的实体用了virtual属性,应该是用ORM框架来做数据持久化的):

场景1:获取患者最新录入的Plan中的所有非空子计划

这种场景是假设你要找的是该患者最近一次录入的Plan记录里,所有不为null的子计划。这是最常见的需求,实现起来也最直接高效:

高效查询实现

// 目标患者ID
var targetPatientId = 123;

// 直接投影需要的子计划,避免加载整个Plan实体,减少数据传输
var latestSubPlans = await _context.Plans
    .Where(plan => plan.Patient.Id == targetPatientId)
    .OrderByDescending(plan => plan.Date) // 按录入日期倒序,取最新的Plan
    .Select(plan => new 
    {
        Child1 = plan.PlanChild1,
        Child2 = plan.PlanChild2,
        // 这里依次列出所有子计划属性,比如PlanChild3、PlanChild4等
    })
    .FirstOrDefaultAsync();

// 过滤出非null的子计划
var result = new List<PlanDetail>();
if (latestSubPlans != null)
{
    if (latestSubPlans.Child1 != null) result.Add(latestSubPlans.Child1);
    if (latestSubPlans.Child2 != null) result.Add(latestSubPlans.Child2);
    // 对应上面的子计划属性,逐一判断添加
}

优化建议

为了让这个查询更快,建议给Plans表创建联合索引,覆盖PatientId和Date字段:

CREATE INDEX IX_Plans_PatientId_Date ON Plans (PatientId, Date DESC);

这个索引能让数据库快速定位到特定患者的最新Plan记录,避免全表扫描。


场景2:获取每个子计划类型的最新记录

如果你的需求是:针对每个子计划类型(比如PlanChild1、PlanChild2),找到该患者所有Plan中最新录入的那个子计划实例(比如PlanChild1可能在多个Plan里都有值,要取最新的那个),可以用窗口函数来实现:

查询实现

var targetPatientId = 123;

var latestSubPlansByType = await _context.Plans
    .Where(plan => plan.Patient.Id == targetPatientId)
    // 将每个Plan的子计划转换成(子计划实例, 录入日期)的集合
    .SelectMany(plan => new List<(PlanDetail SubPlan, DateTime RecordDate)>
    {
        (plan.PlanChild1, plan.Date),
        (plan.PlanChild2, plan.Date),
        // 列出所有子计划属性
    })
    .Where(item => item.SubPlan != null) // 过滤掉null的子计划
    .GroupBy(item => item.SubPlan.GetType()) // 按子计划类型分组
    .Select(group => group.OrderByDescending(item => item.RecordDate).First().SubPlan)
    .ToListAsync();

这个查询会把每个子计划类型的最新实例都筛选出来,适合需要分别追踪每种子计划最新状态的场景。


内容的提问来源于stack exchange,提问作者Mohammad Shadmehr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:32:11