C# 在CosmosClient中使用LINQ查询时查找RequestCharge

C# 在CosmosClient中使用LINQ查询时查找RequestCharge,c#,azure-cosmosdb,C#,Azure Cosmosdb,当我使用createitemsync时,我会得到一个itemsresponse,它允许我访问RU中的RequestCharge,并可能将其记录下来,这样我就可以准确地了解RU的用法 但是,当使用LINQ查询CosmosClient时,我看不到任何获取RequestCharge的方法。查看RequestCharge非常有用,但它只有在以某种方式查询时才可用,这似乎是错误的,所以我想我肯定遗漏了什么 这是我的代码示例 var tenantContainer = cosmos.GetContainer

当我使用
createitemsync
时,我会得到一个
itemsresponse
,它允许我访问RU中的
RequestCharge
,并可能将其记录下来,这样我就可以准确地了解RU的用法

但是,当使用LINQ查询CosmosClient时,我看不到任何获取RequestCharge的方法。查看RequestCharge非常有用,但它只有在以某种方式查询时才可用,这似乎是错误的,所以我想我肯定遗漏了什么

这是我的代码示例

var tenantContainer = cosmos.GetContainer("myapp", "tenant");
var query = tenantContainer.GetItemLinqQueryable<Tenant>(true, null, 
    new QueryRequestOptions { PartitionKey = new PartitionKey("all") })
    .Where(r => r.AccountId = "1234");

var tenants = query.ToList();
//track.Metric("GetTenants", cosmosResponse.RequestCharge);
var-tenantContainer=cosmos.GetContainer(“myapp”、“tenant”);
var query=tenantContainer.GetItemLinqQueryable(true,null,
新查询请求选项{PartitionKey=new PartitionKey(“all”)})
其中(r=>r.AccountId=“1234”);
var tenants=query.ToList();
//track.Metric(“GetTenants”,cosmosResponse.RequestCharge);

请注意,我使用的是“新的”
CosmosClient
,而不是旧的
DocumentClient

请确保包含此using语句

using Microsoft.Azure.Cosmos.Linq;
然后可以使用
.ToFeedIterator()
,它包含一个带有
RequestCharge
的属性

以下是完整的代码示例:

var container = _cosmos.GetContainer("mydb", "user");

// Normal linq query
var query = container.GetItemLinqQueryable<Shared.Models.User>(true, null,
    new QueryRequestOptions { PartitionKey = new PartitionKey(tenantName) })
    .Where(r => r.Email == loginRequest.Email);

// Instead of getting the result, first convert to feed iterator
var iterator = query.ToFeedIterator();

// And finally execute with this command that also supports paging
var cosmosResponse = await iterator.ReadNextAsync();

// And then the RequestCharge is readily available
_track.Metric("GetUserForAuthentication", cosmosResponse.RequestCharge);

// And whatever linq execution you wanted to do, you can do on the response
var user = cosmosResponse.FirstOrDefault();
var container=\u cosmos.GetContainer(“mydb”,“user”);
//正常linq查询
var query=container.GetItemLinqQueryable(true,null,
新查询请求选项{PartitionKey=new PartitionKey(tenantName)})
.Where(r=>r.Email==loginRequest.Email);
//首先转换为feed迭代器,而不是获取结果
var iterator=query.ToFeedIterator();
//最后使用这个也支持分页的命令执行
var cosmosResponse=await iterator.ReadNextAsync();
//然后,申请费用就可以随时获得
_Metric(“GetUserForAuthentication”,cosmosResponse.RequestCharge);
//无论您想执行什么linq,都可以对响应执行
var user=cosmosResponse.FirstOrDefault();

我还没有尝试过这个方法,但是如果您对查询执行了
ToFeedIterator()
,您可以调用
ReadNextAsync()
,同时有更多的结果,这会给您一个
ResponseMessage
并且有一个
Header
属性,其中包含
x-ms-request-charge
。很简单,对吧?是的,成功了!你想发布答案吗?然后,作为问题的一部分,我将用代码详细说明解决方案?只是一个提示,在“ToFeedIterator”出现之前,您必须包括“使用Microsoft.Azure.Cosmos.Linq”。您可以回答并接受自己的问题,我很高兴它起到了作用。我自己可能会将此作为参考。谢谢@Crowcoder-我在下面给出了一个答案,我希望其他寻求相同问题解决方案的人都能明白。