Reputation: 720
Trying to write a function that inserts items into an Azure Table from a function (working). I would like to capture the scenario where the item already exists - therefore I'd like to Query/Read/Execute on the Table and if the item is not found, Insert:
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);
}
}
}
I have tried outputTable.Execute TableOperation.Retrieve But nothing works and the intellisense in the Portal tool is rubbish.
Because it is Async, the insert cannot be caught in an Exception() block. Any ideas?
Upvotes: 2
Views: 568
Reputation: 3293
Use the CloudTable
method parameter to get a reference to the table which you can then perform queries and operations on:
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("");
}
Edit: I just re-read the question and see you are using the portal so I assume C# script. See an example here https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-storage-table#input---c-script-example---cloudtable - the logic will be the same.
Upvotes: 2