async query in cosmos db

Viewed 1799

I'm trying to do a query in cosmos db. I want a async query. The query return me only one element. In the web I have seen how to do it when query return more than one element. This is my method:

    public async Task<TenantDetails> ReadBrokerSettings(string tenantId)
    {
        FeedOptions queryOptions = new FeedOptions { MaxItemCount = -1 };

        var tenantDTO = this._client.CreateDocumentQuery<TenantDTO>(
             UriFactory.CreateDocumentCollectionUri(_idDatabase, _idCollection), queryOptions)
             .Where(f => f.tenantId == tenantId)
             .AsEnumerable()
             .SingleOrDefault();

        return tenantDTO != null ? _iTenantAssembler.DtoToEntity(tenantDTO) : null;
    }

Compiler say me than it isn't async. Thanks

1 Answers

That's because it's not async. You need to convert it to a document query and use the HasMoreResults + ExecuteNextAsync combination and use the await keyword on the ExecuteNextAsync.

Here is a working example:

public async Task<TenantDetails> ReadBrokerSettings(string tenantId)
{
    FeedOptions queryOptions = new FeedOptions { MaxItemCount = 1 };

    var query = this._client.CreateDocumentQuery<TenantDTO>(
         UriFactory.CreateDocumentCollectionUri(_idDatabase, _idCollection), queryOptions)
         .Where(f => f.tenantId == tenantId).AsDocumentQuery();

    while(query.HasMoreResults)
    {
        var results = await query.ExecuteNextAsync();
        if(results.Any())
        {
            return _iTenantAssembler.DtoToEntity(results.Single());
        }
    }

    return null;
}
Related