gpt4 book ai didi

c# - ExecuteStoredProcedureAsync() 返回不同的结果

转载 作者:行者123 更新时间:2023-12-03 05:39:15 24 4
gpt4 key购买 nike

长话短说,cosmosDB 中的存储过程在门户内执行时返回 2,而在我的 c# 控制台应用程序中从 ExecuteStoredProcedureAsync() 调用时返回 0。正确答案是2

这是存储过程:

JS:

function countItems() {
var context = getContext();
var collection = context.getCollection();
var collectionLink = collection.getSelfLink();
var response = context.getResponse();

var query = "SELECT * FROM c";

var isAccepted = collection.queryDocuments(
collectionLink,
query,
function(err, documents, responseOptions) {
if (err) {
throw err;
}
response.setBody(documents.length);
}
);
}

当我从 azure 门户运行此命令时,它返回正确的结果:2。

//////////////////////

这是 C# 调用:

C#

private static async Task ExecuteStoredProc(string spId, CosmosContext cosmosContext)
{
using (var client = new CosmosClient(cosmosContext.Endpoint, cosmosContext.MasterKey))
{
var container = client.GetContainer(cosmosContext.DbId, cosmosContext.ContainerId);
var scripts = container.Scripts;
var pk = new PartitionKey(cosmosContext.DbId);
var result = await scripts.ExecuteStoredProcedureAsync<string>(spId, pk, null);
var message = result.Resource;

Console.WriteLine(message);
}
}

当我从 C# 控制台应用程序运行它时,它返回 0

这是怎么回事?

最佳答案

根据我的测试,您可能没有正确设置PartitionKey

如果您设置了分区键,则需要传递正确的分区键。

static void Main(string[] args)
{
using (var client = new CosmosClient(Endpoint, Key))
{
// With Partition Key
var container = client.GetContainer("TestDB", "Demo");

var scripts = container.Scripts;

// With Partition Key
var pk = new PartitionKey("B");
var result =scripts.ExecuteStoredProcedureAsync<string>("length", pk, null).GetAwaiter().GetResult();

var message = result.Resource;
Console.WriteLine(message);
}
Console.ReadLine();
}

enter image description here

enter image description here

如果没有分区键,则需要传递PartitionKey.None

static void Main(string[] args)
{
using (var client = new CosmosClient(Endpoint, Key))
{
// Without Partition Key
var container = client.GetContainer("ToDoList", "Items");

var scripts = container.Scripts;

//Without Partition Key
var result = scripts.ExecuteStoredProcedureAsync<string>("length", PartitionKey.None, null).GetAwaiter().GetResult();

var message = result.Resource;
Console.WriteLine(message);
}
Console.ReadLine();
}

enter image description here

enter image description here

关于c# - ExecuteStoredProcedureAsync() 返回不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59996385/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com