0

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();
        }
Cenk
  • 13
  • 1
  • 10

2 Answers2

4

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

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Can I make it async? I am going to use this in my generic repository of asp.net web api solution. – Cenk Jul 03 '19 at 12:16
3

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.

DavidG
  • 113,891
  • 12
  • 217
  • 223
  • @MarcGravell Yup, good point, I should have been more explicit. – DavidG Jul 03 '19 at 12:10
  • How can I make the GetManyQueryable async? – Cenk Jul 03 '19 at 12:28
  • It's returning an `IQueryable`, if you want async you need to materialise the data, for example with a `ToListAsync`. I would advise to not return the `IQueryable` in the first place. – DavidG Jul 03 '19 at 12:29
  • Is this OK? `public virtual async Task> GetGamesAsync( Expression> where ) { return await dbSet.Where(where).ToListAsync(); }` – Cenk Jul 03 '19 at 12:32
  • Depends on what you mean by "OK", but yes, that will work. – DavidG Jul 03 '19 at 12:33