如何异步使用 EF Core 扩展方法
How to use EF Core extension methods asynchronously
我有一个带表达式的过滤方法,如下所示:
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;
}
但是现在想在实际函数中调用这个filter方法
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();
}
这是异步的:
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 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.
我有一个带表达式的过滤方法,如下所示:
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;
}
但是现在想在实际函数中调用这个filter方法
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();
}
这是异步的:
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 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.