c# - Azure表存储: adding item if it does not exist

标签 c# azure azure-table-storage

我正在使用 Azure 表存储并使用 CloudTable 对象(在 Microsoft 的库 Microsoft.Azure.Cosmos.Table 中)来添加记录。目前我有这个:

鉴于我的 CloudTable 对象是这样的: 私有(private)只读CloudTable cloudTable;

我有以下代码来更新插入记录:

var upsertOp = TableOperation.InsertOrReplace(myRecord);
cloudTable.ExecuteAsync(upsertOp);

但是,我想做的是仅在记录尚不存在时添加新记录。如果已经存在,那么我不想添加或更新现有的。

执行此操作的正确方法是什么?我是否以某种方式使用事务,或者我可以使用 TableOperation.Insert() 方法(我假设如果项目已存在,这将引发异常)?

最佳答案

没有直接的方法来检查记录是否在 Azure 表存储中。

这里有两种方法可以做到这一点:

1.正如您提到的,您可以直接将 TableOperation.Insert() 方法与 try-catch 一起使用。如果记录已经存在,则会抛出错误:

   try
    {
        var op1 = TableOperation.Insert(c1);
        table.Execute(op1);
    }
    catch (Exception ex)
    {
        //if the record already exists, an error will be thrown.

    }

2.您还可以使用TableOperation.Retrieve()方法。如果没有返回记录,可以插入一条新记录。否则,您不需要插入新的:

        TableOperation retrieveOperation = TableOperation.Retrieve<CustomerEntity>("partition_key", "row_key");
        TableResult result = table.Execute(retrieveOperation);

        CustomerEntity customer = result.Result as CustomerEntity;
        if (customer != null)
        {
            //if it's not null, you don't need to insert a new record.
        }
        else
        {
            //if it's null, you can insert a new record.
        }

关于c# - Azure表存储: adding item if it does not exist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65346517/

相关文章:

c# - 使用反射将事件处理程序绑定(bind)到任何类型的事件

azure - AKS RBAC - 角色绑定(bind)无效

WebAPI2 中的 Azure AD 图形请求

c# - 查询 azure 表中的多个实体

azure - 使用 Azure 流分析 HoppingWindow 函数进行事件处理(每天 1700 万个事件) - 24 小时窗口,1 分钟跳跃

c# - 如何在 XAML 中设置 DataGrid 的 ItemsSource?

C# 正则表达式获取字符串直到模式

c# - 你如何在winforms中使用通用对象绑定(bind)?

asp.net - 将 ASP.Net 应用程序迁移到 Azure

Azure 表存储 - CreateIfNotExistsAsync 上的 501 NotImplemented