Search code examples
azureazure-cosmosdbazure-table-storageazure-cosmosdb-tables

Microsoft.Azure.Cosmos.Table - How could I retrieve an item operation status if it is inserted or merged using insertOrMergeOperation?


I'm recently using the Microsoft.Azure.Cosmos.Table API and I noticed there was a great method called InsertOrMergeOperation, however, I am wondering if there is any way that the return result could tell me whether my entity just did an insert or a merge/update operation. I checked the TableResult object but it doesn't return any useful information about that.

Is there anyone know if this Operation could give me what I want? If not, is there any other operation that could perform the same workflow?


Solution

  • The TableResule does not return a value to indicate if it's an insert or merge operation. If you want to get the info, you have 2 methods for that:

    Method 1:use table query with partition key and rowkey to check if the records exists or not in table, then you know the following operation by InsertOrMerge() is insert or merge as per the result is null or not, sample code like below:

    CloudTableClient tableClient = account.CreateCloudTableClient();
    CloudTable table = tableClient.GetTableReference("People");
    
    TableQuery<CustomerEntity> query = new TableQuery<CustomerEntity>()
        .Where(
            TableQuery.CombineFilters(
                TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "Smith"),
                TableOperators.And,
                TableQuery.GenerateFilterCondition("Email", QueryComparisons.Equal,"Ben@contoso.com")
        ));
    
    await table.ExecuteQuerySegmentedAsync<CustomerEntity>(query, null);
    

    Method 2:use try-catch block, and first do a insert operation, if it returns an "conflict" error message, means the following InsertOrMerge() operation is an merge operation, code like below:

                TableOperation t1;
    
                try
                {
                    t1 = TableOperation.Insert(customer);
                    table.Execute(t1);
                }
                catch (Exception e)
                {
                    if (e.Message.ToLower() == "Conflict".ToLower())
                    {
                        t1 = TableOperation.InsertOrMerge(customer);
                        table.Execute(t1);
                    }
                }
    

    Hope it helps.