Search code examples
c#azureexceptionazure-cosmosdbdocumentclient

DocumentClient.CreateDocumentQuery throws a "not an instance" error when running a query


I'm writing a .NET web service that takes documents from a cosmosDB database. I writing a function in another project (that is supposed to be as generic as possible) to retrieve a document, so that the WS will use it.

I'm using DocumentClients function CreateDocumentQuery like this:

public static async Task<T1> GetMyDocumentAsync<T1>(eDataBase databaseName, eCollection collectionName, eFields key, string val)
{
    var option = new FeedOptions { EnableCrossPartitionQuery = true };
    Uri uri = UriFactory.CreateDocumentCollectionUri(databaseName.ToString(), collectionName.ToString());
    IQueryable<T1> res = Client.CreateDocumentQuery<T1>(uri, option);
    document = res.AsEnumerable<T1>().FirstOrDefault();
}

This works fine, returning the first document in the database. But changing the usage of CreateDocumentQuery to this:

IQueryable<T1> res = Client.CreateDocumentQuery<T1>(uri, "SELECT * FROM c",option);

And wrapped inside a try-catch block throws an exception that has an InnerException that states:

Object not set to an instance of an object.

Also some of the exception fields are:

Data = {System.Collections.ListDictionaryInternal}

and

Error = {{ "code": "BadRequest",
           "message": "\r\nActivityId: SOMEGUID" }}

The query works on that collection from the azure portal.

The client properties I'm using are:

ConnectionMode = Gateway and Protocol = Https.

Any ideas as to why this usage works and the other using an explicit query string won't? I also tried using a SqlQuerySpec object and the result was the same. I don't want to use the Where() function since I want to use generic types. The async keyword was meant for future use.


Solution

  • So I solved it.

    When creating the collection I tried to query in the question, I noticed that a partition key is mandatory. All my other collections up in cosmos did not have any. So I figured that some of the settings should be different for collections that do have partition keys.

    The part that throw the null exception was enumerating the document query. The function usage looked OK according to the documentation so I thought that the problem was with the CreateDocumentQuery. That is because it created a "faulty" object, with some null fields and it might be due to the change in collection partition keys.

    So I tried updating the package Microsoft.Azure.DocumentDB for my entire solution to the lastest stable version (2.2.0 at the time being) and then it just worked.