How to use EF Core extension methods asynchronously

Viewed 526

I have a filter method with expression, like this :

public IQueryable<Alert> GetAlerts(Expression<Func<Alert, bool>> filter, bool includeDone = false)
{
    var query = _patientDbContext.Alerts
                .Where(filter);

    if (!includeDone)
    {
        query = query.Where(i => !i.IsDone);
    }

    query = query.OrderBy(i => i.Deadline);

    return query;
}

But now I want to call this filter method in the actual function

public async Task<List<Alert>> GetAllAlertsForOrganisation(int organisationId, DateTime? beginDate, DateTime? endDate)
{
    var query2 = GetAlerts(i => i.OrganisationId == organisationId && (beginDate == null || i.CreatedAt <= endDate) &&
                (endDate == null || i.CreatedAt >= beginDate)).ToList();

    return await ....//What to call the GetAlerts method?
                .ToListAsync();
}
1 Answers

This is asynchronous:

var query2 = GetAlerts(i => i.OrganisationId == organisationId && (beginDate == null || i.CreatedAt <= endDate) && (endDate == null || i.CreatedAt >= beginDate));

return await query2.ToListAsync();

As @weichch has mentioned, GetAlerts doesn't execute anything in the database:

Entity Framework Core provides a set of async extension methods similar to the LINQ methods, which execute a query and return results. Examples include ToListAsync(), ToArrayAsync(), SingleAsync(). There are no async versions of some LINQ operators such as Where(...) or OrderBy(...) because these methods only build up the LINQ expression tree and don't cause the query to be executed in the database.

Related