我正在使用 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/