0

我们可以使用哪种方法(或方法组合)来使我们能够插入、更新和删除实体?

有几种方法可以绑定到表存储:

如果您只有 1 个正在检索的实体并且您的触发器具有查询该 1 条记录所需的所有信息,则此方法非常有用:

[Table("MyTable", "MyPartition", "{queueTrigger}")] MyPoco poco

使用v1 函数,我们能够像这样绑定以进行查询(不幸的是,这在 v2 中不可用):

[Table("MyTable", "MyPartition")] IQueryable<MyPoco> pocos

我们可以绑定CloudTable

[Table("AzureWebJobsHostLogscommon")] CloudTable cloudTable

最后,我们可以绑定IAsyncCollector

[Table("mytable", "mypartition")] IAsyncCollector<MyPoco> MyPoco

我们可以使用哪种方法(或方法组合)来使我们能够插入、更新和删除实体?

4

1 回答 1

0

绑定CloudTable

[Table("AzureWebJobsHostLogscommon")] CloudTable cloudTable

然后您可以使用TableOperation该类来插入、更新和删除实体:

TableOperation insert = TableOperation.InsertOrReplace(entity);
TableOperation delete = TableOperation.Delete(entity);
TableOperation replace = TableOperation.Replace(entity);
TableOperation merge = TableOperation.Merge(entity);
... etc

await cloudTable.ExecuteAsync(insert);
await cloudTable.ExecuteAsync(delete);
await cloudTable.ExecuteAsync(replace);
await cloudTable.ExecuteAsync(merge);
... etc

完整示例:

public class MyEntity : TableEntity
{
    public string Name { get; set; }
}

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

        var myEntity = new MyEntity
        {
            PartitionKey = Guid.NewGuid().ToString(),
            RowKey = Guid.NewGuid().ToString(),
            Name = "chris"
        };

        TableOperation insert = TableOperation.InsertOrReplace(myEntity);

        await cloudTable.ExecuteAsync(insert);

        return new OkObjectResult(null);
    }
}
于 2019-11-21T12:32:08.607 回答