c# - 从 azure 函数运行 azure 存储过程

标签 c# .net-core azure-cosmosdb azure-functions

是否可以从 azure 函数运行 Cosmos DB 存储过程(在 azure 门户中创建的 sp)(例如时间触发器)。

我需要的是按时间触发器查询集合中的文档(输入绑定(bind)),修改其中的某些字段并更新(如DocumentClient.UpsertDocumentAsync)并将更新的文档存储回集合中。

最佳答案

第 1 步:请在 Cosmos 数据库中创建存储过程。

示例存储过程 js 代码:

function sample() {
    var collection = getContext().getCollection();

    var isAccepted = collection.queryDocuments(
        collection.getSelfLink(),
        'SELECT * FROM root r where r.id = "1"',
    function (err, feed, options) {
        if (err) throw err;

        if (!feed || !feed.length) {
            var response = getContext().getResponse();
            response.setBody('no docs found');
        }
        else {
            var a = new Date();
            var doc = feed[0];
            doc.time = a;
            collection.replaceDocument(doc._self,doc,function(err) {
                                                        if (err) throw err;
                                                     });
            var response = getContext().getResponse();
            response.setBody(JSON.stringify("update success"));
        }
    });

    if (!isAccepted) throw new Error('The query was not accepted by the server.');
}

第 2 步:创建 C# Azure 函数 TimeTrigger。

示例函数代码:

using System;
using Microsoft.Azure.Documents.Client;


public static void Run(TimerInfo myTimer, TraceWriter log)
{
    private static DocumentClient client;

    static string endpoint = "https://***.documents.azure.com:443/";
    static string key = "***";
    client = new DocumentClient(new Uri(endpoint), key);
    StoredProcedureResponse<bool> sprocResponse = await client.ExecuteStoredProcedureAsync<bool>(
                                                                "/dbs/db/colls/coll/sprocs/updatetest/");
    if (sprocResponse.Response) log.Info(sprocResponse.Response);
    log.Info($"Cosmos DB is updated at: {DateTime.Now}");
}

第 3 步:在 azure-functions 中添加文档数据库程序集引用。

您可以点击Azure功能>查看文件>添加一个名为'project.json'的新文件(如果不存在)。在此文件中写入以下代码,然后单击运行安装包:

{
  "frameworks": {
    "net46":{
      "dependencies": {
        "Microsoft.Azure.DocumentDB": "1.20.1"
      }
    }
   }
}

更多详情,可以引用这个doc .

希望对您有帮助。

关于c# - 从 azure 函数运行 azure 存储过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48665963/

相关文章:

javascript - 当项目部署到暂存时,System.IO.FileNotFoundException 在本地工作正常

docker - 如何使用ASP.Net Core从Docker容器连接到DB2?

.net - 在 .NET Core 2.2 上找不到 AddHealthChecks().AddUrlGroup()

c# - 如何使用 Fluent Assertions 来测试不等式测试中的异常?

c# - 给自己添加一个对象列表?

c# - C# 编译器如何使用泛型?

azure - SignalR 部署在云上时滞后? | .Net核心

c# - 有没有删除cosmos DB文档的c#代码

Azure CosmosDB REST 创建文档时出错

azure-cosmosdb - 唯一 ID 是 CosmosDB 的最佳分区键