If your class definitions have virtual ICollection, you can use them:
public class Patient
{
public int Id { get; set; }
...
// every Patient has zero or more Visits (one-to-many)
public virtual ICollection<Visit> Visits {get; set;}
}
public class Visit
{
public int Id {get; set;}
public DateTime VisitDate { get; set; }
...
// Every Visit is done by exactly one Patient, using foreign key
public int PatiendId {get; set;}
public virtual Patient Patient { get; set; }
}
Requirement: give me from every Patient his latest visit time
var result = dbContext.Patients
.Where(patient => ...) // only if you don't want all Patients
.Select(patient => new
{
// Select from every Patient only the properties you plan to use
Id = patient.Id,
Name = patient.Name,
...
LastVisitTime = patient.Visits
.OrderByDescenting(visit => visit.VisitDate)
.FirstOrDefault(),
});
If you can't use the virtual ICollections, you'll have to do the GroupJoin yourself:
var result = dbContext.Patients.GroupJoing(dbContext.Visits,
patient => patient.Id, // from every Patient take the Id
visit => visit.PatientId, // from every Visit take the PatientId,
(patient, visits) => new // use every patient with all his matching Visits
{ // to make a new object
Id = patiend.Id,
Name = patient.Name,
...
LastVisit = visits.OrderByDescending(visit => visit.VisitDate)
.FirstOrDefault(),
});