I'm using Azure Table Storage and using CloudTable object (in Microsoft's library Microsoft.Azure.Cosmos.Table) to add a record. At the moment I have this:
Given my CloudTable object is this:
private readonly CloudTable cloudTable;
I have the following code to Upsert a record:
var upsertOp = TableOperation.InsertOrReplace(myRecord);
cloudTable.ExecuteAsync(upsertOp);
However, what I want to do is add a new record only if a record does not already exist. If one already exists then I do not want to add or update the existing.
What is the right approach to doing this? Do I use transactions in some way or can I use the TableOperation.Insert() method (I'm assuming this will throw an exception if an item already exists)?
There is no direct way to check if a record is in the azure table storage or not.
So here are 2 ways to do that:
1.As you mentioned, you can directly use TableOperation.Insert() method with try-catch. If the record already exists, it will throw an error:
try
{
var op1 = TableOperation.Insert(c1);
table.Execute(op1);
}
catch (Exception ex)
{
//if the record already exists, an error will be thrown.
}
2.You can also use the TableOperation.Retrieve() method. If there is no record returned, you can insert a new one. Otherwise, you don't need to insert a new one:
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.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With