简体   繁体   中英

Entity Framework Joining multiple tables and display multiple data sets

this is my code to fetch data from multiple table and return it as json. However it only allow one to one relationship.

Problem: DoctorNote have multiple result sets, i am having problem fetching the data. Error"Sequence contains more than one element". Any suggestion on how i can fetch the many relationship results?

    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);

Exception is thrown by SingleOrDefault method, so based on that fact it seems your query returns more than one element.

To get collection of DoctorNotes , just remove SingleOrDefault method from your query

You are using SingleOrDefault() which assume that your query will return at most one record. You may try FirstOrDefault() it assume query can return any number of record and you want first. You may see this to understand difference between the two

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

The query still returns 3 DocterNotes. The FirstOrDefault is on the total query, not on the DocterNotes.

Can you add a where clause? For example, this should work:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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