简体   繁体   中英

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?

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).

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM