温馨提示:本文翻译自stackoverflow.com,查看原文请点击:c# - ExecuteStoredProcedureAsync() returning different results

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

发布于 2020-03-29 13:15:26

简而言之,cosmosDB中的存储过程在门户网站内部执行时返回2,而ExecuteStoredProcedureAsync()在我的c#控制台应用程序中调用时返回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

这是怎么回事?

查看更多

查看更多

提问者
Chris Phillips
被浏览
46
Jack Jia 2020-01-31 17:45

根据我的测试,您可能没有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();
}

在此处输入图片说明

在此处输入图片说明

如果没有分区键,则需要通过 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();
}

在此处输入图片说明

在此处输入图片说明

发布
问题

分享
好友

手机
浏览

扫码手机浏览