EF多表关联:Patient与DoctorNote一对多关系下如何获取多指定DoctorNoteID?
解决Patient与DoctorNote一对多查询仅返回单个关联记录的问题
嘿,我看你遇到了个头疼的问题——明明Patient和DoctorNote是一对多的关系,想同时拿到doctorNoteID为3和4的数据,结果只返回了ID为3的单条记录。咱们来拆解一下问题,然后给你两个靠谱的解决办法。
问题根源
你现在用的是手动join操作来关联表,EF在处理这种join的时候会把结果扁平化,相当于每个Patient对应一条DoctorNote记录。如果没有做分组或者用导航属性加载关联数据,查询结果只会返回第一条匹配的记录,自然就拿不到所有符合条件的DoctorNote了。
方案一:用EF导航属性(推荐,更简洁)
如果你的Patient实体已经定义了导航属性(比如public ICollection<DoctorNote> DoctorNotes { get; set; }),那直接用Include加载关联数据,再筛选符合条件的DoctorNote就行,代码更清晰:
public IHttpActionResult testing(int patientID, string token) { // 先找到目标Patient,同时加载关联的DoctorNotes var patientWithNotes = _context.Patients .Include(p => p.DoctorNotes) .Where(p => p.patientID == patientID) // 筛选出doctorNoteID为3或4的记录,单独提取出来 .Select(p => new { PatientInfo = p, TargetDoctorNotes = p.DoctorNotes.Where(dn => dn.doctorNoteID is 3 or 4) }) .FirstOrDefault(); if (patientWithNotes == null) { return NotFound(); } return Ok(patientWithNotes); }
方案二:手动join后分组聚合
如果你坚持要用手动join的方式,那必须对查询结果按Patient分组,把同一个Patient下的所有符合条件的DoctorNote聚合到一个集合里:
public IHttpActionResult testing(int patientID, string token) { var person = (from p in _context.Patients join e in _context.PatientAllocations on p.patientID equals e.patientID join d in _context.DoctorNotes on p.patientID equals d.patientID // 同时过滤PatientID和目标DoctorNoteID where p.patientID == patientID && (d.doctorNoteID == 3 || d.doctorNoteID == 4) // 按Patient分组,把对应的DoctorNotes聚合起来 group d by p into patientGroup select new { Patient = patientGroup.Key, DoctorNotes = patientGroup.ToList() }) .FirstOrDefault(); if (person == null) { return NotFound(); } return Ok(person); }
这样调整之后,你就能同时拿到doctorNoteID为3和4的所有关联数据啦。
内容的提问来源于stack exchange,提问作者user2837162
相关产品推荐
相关产品推荐

