尝试编写一个函数,将项目从函数插入到 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/