Search code examples
c#azurenosqlazure-storage

How to update Azure Storage Table one specific property values using other property value in where condition?


Let's consider I have the following table storage table NAMED Tbl_ResourceCost.

enter image description here

Now, I want to update Extended cost by using partition key and ResourceGuID. So, if I pass xxx01 as PartitionKey & zzz01 as ResourceGuID in WHERE condition, then it will update only my extendedCost of (i.e. 100 & 200) to let's say 700.

If we consider it in SQL to update, then the query would be, "UPDATE Tbl_ResourceCost set ExtendedCost=700 where PartitionKey=xxx01 and ResourceGuID=zzz01". It will update both 100 & 200 to 700 in a single execution.

I am looking for similar query in C# to update in Azure Storage Table. I am using the NuGet Package as : Microsoft.Azure.Cosmos.Table


Solution

  • If you want to update the Azure table storage entity's properties, we need to provide partition key and row key. For more details, please refer to here. So according to your need, we need to query Azure table storage to get these your need entities then update these.

    For example

    using Microsoft.Azure.Cosmos.Table;
    using System.Threading.Tasks;
    using System;
    namespace Storage
    {
        class Program
        {
            static async Task Main(string[] args)
            {
               
                string connectionString = "";
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
                CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
                var table =tableClient.GetTableReference("test");
    
                TableQuery<MyEntity> myQuery = new TableQuery<MyEntity>().Where(
                        TableQuery.CombineFilters(
                        TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, ""),
                            TableOperators.And,
                        TableQuery.GenerateFilterCondition("ResourceGuID", QueryComparisons.Equal,"")));
    
                foreach (MyEntity entity in table.ExecuteQuery(myQuery))
                {
                    entity.ExtendedCost = ;
                    TableOperation insertOrMergeOperation = TableOperation.InsertOrMerge(entity);
                    TableResult result = await table.ExecuteAsync(insertOrMergeOperation);
                    var s = result.Result as MyEntity;
                   Console.WriteLine(s.ExtendedCost )
                }
    
            }      
        }
    
        public class MyEntity : TableEntity
        {
            public MyEntity()
            {
            }
    
      
            public string ResourceGuID{ get; set; }
    
            public Int32 ExtendedCost { get; set; }
    
        }
    }