2

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();
}
JeremyTCD
  • 695
  • 1
  • 6
  • 11
  • 1
    The `GetAlerts` methods has no async operations why do you need to call it asynchronously? – weichch Mar 29 '20 at 08:17
  • Because it is .net core application. So data comes from database. Otherwise it takes a lot of time to fetch the data –  Mar 29 '20 at 08:18
  • 1
    No, the method is building database query, and won't execute the query. `ToListAsync()` executes the query. – weichch Mar 29 '20 at 08:21
  • @weichch. Yes you are right. But how to call the method? –  Mar 29 '20 at 08:25
  • 1
    You just need `await GetAlerts(alert => alert.IdontKnow == desiredValue).ToListAsync();` – weichch Mar 29 '20 at 08:27

1 Answers1

1

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.

JeremyTCD
  • 695
  • 1
  • 6
  • 11