How do I use the AsQueryable method asynchronously with MongoDb C# Driver 2.1?

rrrr picture rrrr · Dec 2, 2015 · Viewed 7.3k times · Source

The release of version 2.1 of the MongoDb C# Driver has recently reintroduced the method AsQueryable, but I am struggling to find a way of calling it asynchronously.

With Entity Framework this would be achieved using QueryableExtensions.ToListAsync but I can't see an equivalent using MongoDb.

So given a repository method such as:

public IQueryable<MyType> GetFiltered(Expression<Func<MyType, bool>> predicate)
{
        return Database.GetCollection<MyType>(typeof(MyType).Name).AsQueryable().Where(predicate);
}

I wanted to do something like

var myTypes = await MyRepository.GetFiltered(t => t.Id == 1).ToListAsync();

Is this possible?

Answer

JohnnyHK picture JohnnyHK · Jan 7, 2016

You're returning the wrong type from the GetFiltered function. It should be returning an IMongoQueryable<MyType> instead of IQueryable<MyType>:

public IMongoQueryable<MyType> GetFiltered(Expression<Func<MyType, bool>> predicate)
{
    return Database.GetCollection<MyType>(typeof(MyType).Name).AsQueryable()
        .Where(predicate);
}

You can then successfully call it as:

var myTypes = await MyRepository.GetFiltered(t => t.Id == 1).ToListAsync();