从表读取AzureFunction

时间:2019-07-02 14:17:07

标签: 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); 
        }
    }
}

我尝试过 outputTable.Execute TableOperation.Retrieve 但是没有任何效果,并且门户网站工具中的智能感知是垃圾。

由于它是异步的,因此无法在Exception()块中捕获该插入。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

使用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://docs.microsoft.com/en-us/azure/azure-functions/functions-bindings-storage-table#input---c-script-example---cloudtable中查看示例-逻辑将是相同的。