Akash.P
Akash.P

Reputation: 125

DocumentDB SQL Query works in Query Explorer but not in C# code

I want to get value of a variable(InputAssetId) stored in a document as a string.Wrote the query.It works fine in the QueryExplorer.

 this.client = new DocumentClient(new Uri(EndpointUri), PrimaryKey);
 IQueryable<asset> id = this.client.CreateDocumentQuery<asset>(
               UriFactory.CreateDocumentCollectionUri(DatabaseName,CollectionName),
               "SELECT c.InputAssetId FROM c WHERE c.BlobNameDb='BigBuckBunny.mp4' ");
 Console.WriteLine( id.string());

Instead of a value stored in the variable,what i got in the console is given below

{"query":"SELECT c.InputAssetId FROM c WHERE c.BlobNameDb='BigBuckBunny.mp4' "}

Can anyone please give me a solution?

Upvotes: 0

Views: 460

Answers (2)

Sander
Sander

Reputation: 51

The issue is that you aren't actually ever executing the query you've created. The correct code would be something along those lines:

this.client = new DocumentClient(new Uri(EndpointUri), PrimaryKey);
var query = this.client.CreateDocumentQuery<asset>(
         ... your LiNQ or SQL query...
    .AsDocumentQuery();

var result = await query.ExecuteNextAsync<string>();
Console.WriteLine(result.ToList().FirstOrDefault());

You may want to use TOP 1 in the query (and not FeedOptions.MaxItemCount = 1, as the latter is badly named - it actually means how many items per feed request are returned at the most. Using low MaxItemCount can lead to great number of useless queries).

Upvotes: 1

C.Champagne
C.Champagne

Reputation: 5489

Well I still don't know all the API that well but I would use Linq with C#. `.

You should write it more or less that way :

FeedOptions queryOptions = new FeedOptions { MaxItemCount = 1 };

IQueryable<Asset> assetQuery = client.CreateDocumentQuery<Asset>(UriFactory.CreateDocumentCollectionUri(DatabaseName, CollectionName),

queryOptions) .Where(o => o.BlobNameDb == "BigBuckBunny.mp4");

string id = assetQuery.First().InputAssetId ;

From what I can read in the documentation you want to use SQL query, you have to pass it as a SqlQuerySpec so your code could become (haven't tested the solution though):

IQueryable<string> assetQuery = client.CreateDocumentQuery<Asset>(
          UriFactory.CreateDocumentCollectionUri(DatabaseName, CollectionName), 
          new SqlQuerySpec("SELECT c.InputAssetId FROM c WHERE c.BlobNameDb='BigBuckBunny.mp4'"),
          queryOptions)
string id = assetQuery.First();

Upvotes: 0

Related Questions