如何异步使用EF Core扩展方法

时间:2020-03-29 08:14:49

标签: c# linq asp.net-core iqueryable

我有一个带有表达式的过滤器方法,像这样:

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;
}

但是现在我想在实际函数中调用此过滤器方法

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 个答案:

答案 0 :(得分:1)

这是异步的:

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

return await query2.ToListAsync();

如@weichch所述,GetAlerts doesn't execute anything in the database

Entity Framework Core提供了一组类似于LINQ方法的异步扩展方法,它们执行查询并返回结果。示例包括ToListAsync(),ToArrayAsync(),SingleAsync()。没有某些LINQ运算符的异步版本,例如Where(...)或OrderBy(...),因为这些方法只会建立LINQ表达式树,不会导致查询在数据库中执行。