首页 文章

Azure表存储InsertOrMerge

提问于
浏览
1

我有一个包含一些数据的Azure表存储 . 我需要为表中的所有记录更新一个单独的属性 . 我知道每个项目的分区键和rowkey . 但是可能是因为我的CSV文件中有新项目 .

我需要做的是:

  • 如果在基于ParitionKey和RowKey的表存储中找到一个项目,我想更新一个属性:Name .

  • 如果在表格中找不到某个项目,则必须插入该项目,但我需要填写更多属性:名称,电子邮件,地址

我正在尝试使用InsertOrMerge,但我得到了一个Etag异常,如果找不到该项并且需要插入,我该如何设置更多属性?

CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);

        CloudTableClient cloudTableClient = storageAccount.CreateCloudTableClient();

        CloudTable ct = cloudTableClient.GetTableReference("mytable");



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

        TableOperation to = TableOperation.Merge(code);

        var result = await ct.ExecuteAsync(to);

1 回答

  • 1

    当我使用 Merge 来操作表中不存在的实体时,我也遇到了etag异常 .

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

    您的要求可以通过 RetrieveInsertOrMerge 来实现 .

    将两个属性 EmailAddress 添加到 Item 类 .

    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; }
    
    }
    

    添加if if以告知要加载哪些属性 .

    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 = "test@example.com",
             Address = "Britain"
         }
     }
    
     to = TableOperation.InsertOrMerge(item);
    
     tr = await ct.ExecuteAysnc(to).Result;
    

    . 当你执行 InsertOrMerge 时,

    • 如果该项目存在,其内容(名称)将由您的新项目更新 .

    • 如果它不存在,将按预期插入 .

相关问题