Include
does not filter, it merely includes related data to be loaded eagerly along with the main entity being selected.
To get jobs where the account status is completed and has at least one bid with a status of completed:
db.Jobs.Where(x => x.Account == id
&& x.Status == "Completed"
&& x.Bids.Any(b => b.Status == "Completed"))
.Include(x => x.Account1)
.ThenInclude(b => b.Account1)
.ToListAsync();
The typical thing that trips people up when they return entities is that they'd say "but I only want back the Bids that are completed." This will return back all bids for jobs that are completed and have at least 1 completed bid.
To return back a filtered set of related data to those jobs, use ViewModels/DTOs to return to the views/API consumers rather than returning entities. Entities jobs are to reflect the data state. A job may include many bids, so the entity should reflect the complete data state for that job.
To return completed jobs with their completed bids, define POCO view model classes for the job, bid, etc. then use .Select()
to project the entities into the view models:
var viewModels = db.Jobs
.Where(x => x.Account == id
&& x.Status == "Completed"
&& x.Bids.Any(b => b.Status == "Completed"))
.Select(x => new JobViewModel
{
AccountId = x.Account,
Account = x.Account1.Select(a => new AccountViewModel
{
AccountId = a.Id,
// ...
},
Bids = x.Bids.Where(b => b.Status == "Completed)
.Select(b => new BidViewModel
{
BidId = b.Id,
// ...
}).ToList()
}).ToListAsync();