简体   繁体   中英

Entity Framework querying by related entity

I have 2 entities, Jobs and Appointments:

public class Job
{
    public int JobId { get; set; }
    public ICollection<Appointment> Appointments { get; set; }
}

public class Appointment
{
    [Key]
    public int AppointmentId { get; set; }

    [Required]
    public DateTime AppointmentDate { get; set; }

    [Required]
    [MaxLength(50)]
    public string Type { get; set; }

    public int Job_JobId { get; set; }

    [ForeignKey("Job_JobId")]
    public virtual Job Job { get; set; }
}

How do I return only jobs that have an "Initial" appointment type?

Something like the following (which isn't valid syntax):

jobs = jobs.Where(x => x.Appointments.Where(p => p.Type == "Initial"));

I believe you're looking for Any() to introduce the condition that a job must have at least one Appointment of type "Initial", viz:

var initialJobs = jobs
    .Where(j => j.Appointments.Any(a => a.Type == "Initial"));

Where requires a predicate argument (Func returning a bool), and Any() returns true if at least one element meets the inner predicate ( a.Type == "Initial" )

If you only want to load the appointments for jobs that have the type as Initial, you could also do this:

var jobs = appointments.Where(x => x.Type == "Initial").Select(x => x.Job);

This should give you Appointments inside the jobs that only have the Initial type.

If you wanna return list of jobs as long as the list contain at least one Type == "Initial" , you should use Any() , Your case seem looks like this

var jobs = jobs.Where(x => x.Appointments.Any(p => p.Type == "Initial"));

Or return job if it contains all appointments with Type == "Initial" , you might use Where()

var jobs = jobs.Where(x => 
{
   var appointmentCount = x.Appointments.Count();
   var validAppointments = x.Appointments.Where(p => p.Type == "Initial");

   return  appointmentCount  == validAppointments.Count();
});

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