简体   繁体   中英

Using linq to instantiate objects containing lists of other objects, where query criteria is on inner list

I have a DB table, let's call it 'People', with an Entity associated with it, and a view model class, Person, that contains a list of objects from another table, let's say 'Jobs'. Each job has a length of time held. Using LINQ, I want to make an IQueryable that contains an IQueryable.

The database has a lot of people in it. I want to pull the people whom have had a job longer than 6 months.

What I have is this:

public IQueryable<Person> GetPeople() =>
    Repo<Person>.Get().Select(p => new Person 
    {
        Name = p.Name,
        Jobs = GetJobs(p.Name)
    }).Where(h => h.Jobs.Count() > 0);

public IQueryable<Job> GetJobs(string name) => 
    Repo<Job>.Get().Where(j => j.name == name && j.time > 6);

The problem is that this pulls every person, then queries for jobs for each of them, which is inefficient. Is there a good way of pulling jobs first, then creating a list of people, each with their own list of qualifying jobs?

Normally, I would say you would just do this, if using Entity Frameworks:

var results=db.People.Where(p=>p.Jobs.Any(j=>j.time>6));

This assumes you have a Person class, that is represented by the table People , and the Person class has a navigation property called Jobs that references the Jobs table.

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