Search code examples
c#azureazure-storageazure-table-storage

Azure Table Storage InsertOrMerge


I have an Azure Table Storage that contains some data. I need to update one single property for all records in the table. I know the partition key and rowkey for each item. However might be so that I have new items in my CSV file.

What I need to do is:

  • if an item is found in the table storage based on ParitionKey and RowKey I want to update one single property: Name.
  • if an item is not found in the table it must be inserted but I have more properties that need to be filled: Name, Email, Address

I am trying to use InsertOrMerge but I got an Etag exception and how can I set up more properties if the item is not found and an insert will be required?

var storageAccount = CloudStorageAccount.Parse(connectionString);
var cloudTableClient = storageAccount.CreateCloudTableClient();
var ct = cloudTableClient.GetTableReference("mytable");

var item = new Item()
{
    PartitionKey = "PARTITIONID",
    RowKey = "ROWID",                
    Name = "DEMO",                     
};

var to = TableOperation.Merge(code);
var result = await ct.ExecuteAsync(to);

Solution

  • I also got etag exception when I use Merge to operate a entity not exist in table.

    System.ArgumentException: 'Merge requires an ETag (which may be the '*' wildcard).'

    Your requirement can be achieved by Retrieve and InsertOrMerge.

    Add two properties Email and Address to your Item class.

     public class Item: TableEntity
     {
        public Item(String PartitionKey, String RowKey, String Name, String Email=null, String Address=null)
        {
            this.RowKey = RowKey ;
            this.PartitionKey = PartitionKey;
            this.Name = Name;
            this.Email = Email;
            this.Address = Address;
        }
    
        public Item(){}
    
        public String Name { get; set; }
    
        public String Email { get; set; }
    
        public String Address { get; set; }
    
    }
    

    Add if switch to tell which properties are to load.

     TableOperation to = TableOperation.Retrieve<Item>("PK","RK");
    
     TableResult tr = table.ExecuteAync(to).Result;
    
     var item;
    
     if (tr != null)
     {
         item = new Item
         {
             PartitionKey = "PARTITIONID",
             RowKey = "ROWID",                
             Name = "DEMO",  
         }
     }
     else
     {
         item = new Item
         {
             PartitionKey = "PARTITIONID",
             RowKey = "ROWID",                
             Name = "DEMO",  
             Email = "[email protected]",
             Address = "Britain"
         }
     }
    
     to = TableOperation.InsertOrMerge(item);
    
     tr = await ct.ExecuteAysnc(to).Result;
    

    . When you execute InsertOrMerge,

    • If the item exists, its content(Name) will be updated by your new item.
    • If it doesn't exist, it will be inserted as expected.