【问题标题】:Run azure store procedure from azure function从 azure 函数运行 azure 存储过程
【发布时间】:2018-07-17 20:53:39
【问题描述】:

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

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

【问题讨论】:

  • 是的,您可以从 Azure 函数运行存储过程。剩下的问题我看不懂。
  • SQL 数据库没有绑定,但你可以使用任何你想要的库,比如 Dapper 或普通的 ADO.NET。
  • 我不需要 SQL db,我需要从 Azure Functions 调用 Azure 存储过程。
  • @Crowcoder,请问如何? :)
  • @ValeriyLyuchyn 你问如何调用 CosmosDB 存储过程?你试过ExecuteStoredProcedureAsync 吗?发布您的代码。你强迫人们猜测你想要什么,甚至你在谈论什么数据库

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


【解决方案1】:

第 1 步:请在您的 cosmos db 中创建您的存储过程。

示例存储过程 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

希望对你有帮助。

【讨论】:

  • 我尝试了上面的代码,但出现以下错误。请看一看。 @Jay龚
  • @Antony 你为你的问题打开了一个案例吗?
  • 没有。我们是否需要在执行此代码之前在某处注册 DB、Collection 和 StoredProcedure 或直接在 String 参数中传递它们的名称?
  • @Antony 是的,当然,您需要先创建这些服务和项目,然后才能在 Azure Function 中使用它们。
  • @Antony 我注意到您创建了一个与 azure-function 相关的案例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多