FailedUnitTest
FailedUnitTest

Reputation: 1800

DocumentClient CreateDocumentQuery async

Why is there no async version of CreateDocumentQuery?

This method for example could have been async:

    using (var client = new DocumentClient(new Uri(endpointUrl), authorizationKey, _connectionPolicy))
    {
        List<Property> propertiesOfUser =
            client.CreateDocumentQuery<Property>(_collectionLink)
                .Where(p => p.OwnerId == userGuid)
                .ToList();

        return propertiesOfUser;
    }

Upvotes: 11

Views: 15130

Answers (2)

Michael Freidgeim
Michael Freidgeim

Reputation: 28435

Based on Kasam Shaikh's answer I've created ToListAsync extensions

  public static async Task<List<T>> ToListAsync<T>(this IDocumentQuery<T> queryable)
        {
            var list = new List<T>();
            while (queryable.HasMoreResults)
            {   //Note that ExecuteNextAsync can return many records in each call
                var response = await queryable.ExecuteNextAsync<T>();
                list.AddRange(response);
            }
            return list;
        }
        public static async Task<List<T>> ToListAsync<T>(this IQueryable<T> query)
        {
            return await query.AsDocumentQuery().ToListAsync();
        }

You can use it

var propertiesOfUser = await 
            client.CreateDocumentQuery<Property>(_collectionLink)
                .Where(p => p.OwnerId == userGuid)
                .ToListAsync()

Note that request to have CreateDocumentQuery async is open on github

Upvotes: 8

Kasam Shaikh
Kasam Shaikh

Reputation: 318

Good query,

Just try below code to have it in async fashion.

DocumentQueryable.CreateDocumentQuery method creates a query for documents under a collection.

 // Query asychronously.
using (var client = new DocumentClient(new Uri(endpointUrl), authorizationKey, _connectionPolicy))
{
     var propertiesOfUser =
        client.CreateDocumentQuery<Property>(_collectionLink)
            .Where(p => p.OwnerId == userGuid)
            .AsDocumentQuery(); // Replaced with ToList()


while (propertiesOfUser.HasMoreResults) 
{
    foreach(Property p in await propertiesOfUser.ExecuteNextAsync<Property>())
     {
         // Iterate through Property to have List or any other operations
     }
}


}

Upvotes: 20

Related Questions