问题
I need the number of documents stored in a collection in my Azure Cosmos Db database. How can I get the count using LINQ query on the IQueryable
object?
docDbClient.CreateDocumentQuery<TResult>().Count()
If I do above, I am unable to follow it up with .AsDocumentQuery()
method.
回答1:
This is my async implementation (use Count, for the sync version):
var count = await DocumentClient.
CreateDocumentQuery<T>(CreateCollectionUri(), CreateFeedOptions()).
Where(predicate).
CountAsync();
where predicate is Expression<Func<T, bool>>
回答2:
You can try to use the following code to count the number of documents in your collection.
client = new DocumentClient(new Uri(EndpointUri), PrimaryKey);
IQueryable<int> total = client.CreateDocumentQuery<int>(UriFactory.CreateDocumentCollectionUri("testdb", "testcoll"), "SELECT Value count(1) FROM c", new FeedOptions() { EnableCrossPartitionQuery = true });
Console.WriteLine("total: " + total.AsEnumerable().FirstOrDefault());
Query result:
If you capture the request (using fiddler etc), you will find that the client sdk send the same query {"query":"SELECT VALUE [{\"item\": Count(1)}]\r\nFROM root"}
to the server when you execute your code docDbClient.CreateDocumentQuery<TResult>().Count()
.
来源:https://stackoverflow.com/questions/45183435/how-to-construct-iqueryable-query-using-linq-when-i-just-need-count-without-read