private async Task<bool> IsGoodPersonForSchedule(Person person, int[] usedStaff, string position)
{
//...
var currPersonFlights = await flightStaffRepository
.GetMany()
.Include(elem => elem.Flight)
.Where(elem => IsDateSuitable(elem.Flight.FlightDate.Value))
.Include(elem => elem.Flight.Route)
.ToListAsync();
//...
return true;
}
Eh, either something important is being done in the elided bits here, or this can just be replaced with:
private Task<bool> IsGoodPersonForSchedule(Person person, int[] usedStaff, string position)
=> Task.FromResult(true)
And this is important because you can't push the task part of an operation into a subquery.
If however you have a non-async IsGoodPersonForSchedule and an async IsGoodPersonForScheduleAsync then you can use IsGoodPersonForSchedule within queries and it will become part of the whole query passed to the database. Obtaining the result of the larger query will be async as a whole.
E.g. let's assume that your IsGoodPersonForSchedule was something more like:
private Task<bool> IsGoodPersonForScheduleAsync(Person person, int[] usedStaff, string position)
{
return flightStaffRepository
.GetMany()
.Include(elem => elem.Flight)
.Where(elem => IsDateSuitable(elem.Flight.FlightDate.Value))
.AnyAsync();
}
(Which is probably well off, but I just want an example of something that really does meaningfully get a boolean result from the repository async).
Then if you also had:
private bool IsGoodPersonForSchedule(Person person, int[] usedStaff, string position)
{
return flightStaffRepository
.GetMany()
.Include(elem => elem.Flight)
.Where(elem => IsDateSuitable(elem.Flight.FlightDate.Value))
.Any();
}
That form could be used as part of a wider query, and because it's part of a wider async query then it is still turned into SQL when appropriate, rather than executed non-async within the C#.
The duplication of code is bad, but solvable:
private IQueryable<Flight> FlightsForPerson(Person person, int[] usedStaff, string position)
{
return flightStaffRepository
.GetMany()
.Include(elem => elem.Flight)
.Where(elem => IsDateSuitable(elem.Flight.FlightDate.Value));
}
private Task<bool> IsGoodPersonForScheduleAsync(Person person, int[] usedStaff, string position)
=> FlightsForPerson(person, usedStaff, position).AnyAsync();
private bool IsGoodPersonForSchedule(Person person, int[] usedStaff, string position)
=> FlightsForPerson(person, usedStaff, position).Any();
I'd also note that you have:
return await Task.Factory.StartNew(() => JsonConvert.SerializeObject(result));
This is going to create yet another task that has to be run on another thread rather than the thread handling the previous await. It should be
return JsonConvert.SerializeObject(result);