c# - Azure 函数从表中读取

标签 c# azure azure-functions azure-storage azure-table-storage

尝试编写一个函数,将项目从函数插入到 Azure 表中(工作)。 我想捕获该项目已存在的场景 - 因此我想在表上查询/读取/执行,如果未找到该项目,则插入:

public static async Task<IActionResult> Run(HttpRequest req, ILogger log, IAsyncCollector<StripeHookResponse> outputTable, IAsyncCollector<string> outputQueueItem)
{

    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

    try{

        if(WHAT_GOES_HERE)
        {
            await outputTable.AddAsync(MyItem); 
        }
    }
}

我已经尝试过了 输出表.执行 表操作.检索 但没有任何效果,Portal 工具中的智能感知很垃圾。

因为它是异步的,所以插入不能被 Exception() block 捕获。有什么想法吗?

最佳答案

使用 CloudTable 方法参数获取对表的引用,然后您可以在该表上执行查询和操作:

public class MyItem : TableEntity
{
}

public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req,
    [Table("AzureWebJobsHostLogsCommon")] CloudTable cloudTable,
    ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    MyItem myItem = JsonConvert.DeserializeObject<MyItem>(requestBody);

    // query the table - here I have used the partition key but you could replace "PartitionKey" with any column in your table
    TableQuery<MyItem> query = new TableQuery<MyItem>().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, myItem.PartitionKey));
    IEnumerable<MyItem> entities = await cloudTable.ExecuteQuerySegmentedAsync(query, null);

    // if all items have a unique partition key and the item exists 
    // you should only get one item returned, if not it will be null (default)
    MyItem existingMyItem = entities.FirstOrDefault();

    // if the item is null, you want to insert it into the table
    if (existingMyItem == null)
    {
        // create an InsertOperation for your new item
        TableOperation insertOperation = TableOperation.Insert(myItem);
        await cloudTable.ExecuteAsync(insertOperation);
    }

    return new OkObjectResult("");
}

编辑:我刚刚重新阅读了问题,发现您正在使用门户,因此我假设使用 C# 脚本。请参阅此处的示例 https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-storage-table#input---c-script-example---cloudtable - 逻辑是一样的。

关于c# - Azure 函数从表中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56854527/

相关文章:

c# - 类既扩展了抽象类又实现了接口(interface)

c# - 当一个程序被称为依赖于机器时——这是什么意思?

c# - SQL Server 从 C# 中选择查询执行

Azure 应用程序见解显示 Node js 应用程序的重复日志条目

azure - 如何查找谁在Azure Portal的Keyvault中创建/编辑了 secret ?

c# - 使用 Xamarin/Vision 框架进行 iOS 条码检测

ios - 与 Silveright 和 iPad 客户端一起使用的推荐绑定(bind)是什么

python - Azure函数Python导入错误: libpython3. 6m.so.1.0

javascript - 如何从 Azure Functions JavaScript 函数中获取更详细的错误消息?

azure-functions - 本地 Azure Functions 触发器计时器触发器