繁体   English   中英

实体框架连接多个表并显示多个数据集

[英]Entity Framework Joining multiple tables and display multiple data sets

这是我的代码,用于从多个表中获取数据并将其作为json返回。 但是,它仅允许一对一关系。

问题:DoctorNote具有多个结果集,我在获取数据时遇到问题。 错误“序列包含多个元素”。 关于如何获取许多关系结果的任何建议?

    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
                      where p.patientID == patientID
                      select new
                      {
                              patient_patientID = p.patientID,
                              patient_isDeleted = p.isDeleted,
                              patient_isApproved = p.isApproved,
                              patient_updateBit = p.updateBit,
                              patientallocation_caregiverID = e.caregiverID,
                              patientallocation_doctorID = e.doctorID,
                              DoctorNote_doctorNoteID = d.doctorNoteID,
                              DoctorNote_note = d.note,
                              DoctorNote_createDateTime = d.createDateTime,
                              DoctorNote_patientID = d.patientID,
                              DoctorNote_isApproved = d.isApproved,
                              DoctorNote_isDeleted = d.isDeleted,
                      }).ToList().SingleOrDefault();
        return Ok(person);

SingleOrDefault方法会引发异常,因此基于这一事实,看来您的查询返回了多个元素。

要获取DoctorNotes集合,只需从查询中删除SingleOrDefault方法

您正在使用SingleOrDefault()假定您的查询将最多返回一条记录。 您可以尝试使用FirstOrDefault()假设查询可以返回任意数量的记录,并且您要先执行)。 您可能会看到此信息以了解两者之间的区别

                | 0 values    | 1 value     | > 1 value
FirstOrDefault  | Default     | First value | First value
SingleOrDefault | Default     | First value | Exception

该查询仍然返回3 DocterNotes。 FirstOrDefault在总查询中,而不在DocterNotes中。

您可以添加where子句吗? 例如,这应该工作:

where p.patientID == patientID
and DoctorNote_doctorNoteID == 3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM