Cenk
Cenk

Reputation: 13

Is it possible to write Async IQueryable<TEntity> query?

I would like to query my database table. I wonder if I can convert my query into IQueryable async.

Here is what I have,

var gameBankResult = await (context.GameBanks.Where(g => g.productCode == initiate.productCode)
                .Where(l => l.referenceId == null)
                ).ToListAsync();

How can I transform it into this?

public virtual IQueryable<TEntity> GetManyQueryable(Func<TEntity, bool> where)
        {
            return dbSet.Where(where).AsQueryable();
        }

Upvotes: 0

Views: 487

Answers (2)

DavidG
DavidG

Reputation: 118977

You should be passing around an Expression rather than a Func, otherwise Entity Framework will execute the query immediately, bringing the entire table into memory and filtering locally. For example:

public virtual IQueryable<TEntity> GetManyQueryable(Expression<Func<TEntity, bool>> where)
{
    return dbSet.Where(where);
}

See here for a good description of the difference.

Upvotes: 3

Marc Gravell
Marc Gravell

Reputation: 1062865

Firstly, when using IQueryable<T>, prefer expressions to delegates, i.e.

public virtual IQueryable<TEntity> GetManyQueryable(
    Expression<Func<TEntity, bool>> where)
{
    return dbSet.Where(where);
}

Then you should be able to use:

var query = whatever.Where(
    g => g.productCode == initiate.productCode && g.referenceId == null).ToListAsync();

but to be honest... that isn't much different to what you already have

Upvotes: 4

Related Questions