在Azure表存储中向现有实体添加列

Sam*_*Sam 0 azure-table-storage

我将一些事务数据保存在Azure Table Storage的表中.当我尝试"更新"表中的现有实体并向其添加新列时,看起来它没有添加列.

这是一个例子:我在表格中保存时间表条目.当我第一次创建实体时,有一个StartTime但没有EndTime

PersonId -- TransactionId -- StartTime -- EndTime
Run Code Online (Sandbox Code Playgroud)

所以,当我第一次在表中创建实体时,我最终得到了PersonId, TransactionId and StartTime列.后来,我想添加EndTime但看起来它没有添加它,因为在我的对象EndTime是一个可以为空的属性,当它是时NULL,该列不会被创建.

有没有办法更新现有实体并在流程中添加列?如果没有,我将不得不EndTime在初始创建实体期间放入一些虚拟日期并存储它,以便列存在,我可以稍后更新.

我宁愿不存储任何虚拟数据.

Tom*_*SFT 6

有没有办法更新现有实体并在流程中添加列?

是的,根据您的情况,我们可以通过两种方式实现:编辑事务数据模型或使用 DynamicTableEntity

1.编辑您的事务数据模型并设置Endtime datetime和null值.演示代码如下,

 public class Transactional:TableEntity
    {
        public string PersonId { get; set; }
        public string TransactionId { get; set; }
        public DateTime StarTime { get; set; }
        public DateTime? EndTime { get; set; }

        public Transactional() { }

        // Define the PK and RK
        public Transactional(string persionId, string transactionId)
        {
            PartitionKey = persionId;
            RowKey = transactionId;
        }
    }  
Run Code Online (Sandbox Code Playgroud)

如果我们不将值赋给并尝试向表中插入实体,则没有EndTime列.以下是演示代码.

 CloudStorageAccount storageAccount = CreateStorageAccountFromConnectionString(CloudConfigurationManager.GetSetting("StorageConnectionString"));
 var tableClient = storageAccount.CreateCloudTableClient();
 var table = tableClient.GetTableReference("tableName");
 table.CreateIfNotExists();
 var guid = Guid.NewGuid().ToString();
 Transactional transactional = new Transactional("tomtest", guid);
 transactional.StarTime =DateTime.UtcNow;
 TableOperation insertOrMergeOperation =   TableOperation.InsertOrMerge(transactional);         
 TableResult result = table.Execute(insertOrMergeOperation);    
Run Code Online (Sandbox Code Playgroud)

如何更新实体

 // update entity
 TableOperation retrieveOperation = TableOperation.Retrieve<Transactional>("tomtest", "pk"); //PK, RK
 TableResult retrieveResult = table.Execute(retrieveOperation);
 Transactional updateEntity = retrieveResult.Result as Transactional;
 if (updateEntity != null) updateEntity.EndTime = DateTime.UtcNow;
 TableOperation insertOrMergeOperation = TableOperation.InsertOrMerge(updateEntity);
 // Execute the operation.
 TableResult resultinsertormerge = table.Execute(insertOrMergeOperation);  
Run Code Online (Sandbox Code Playgroud)

2.我们可以用来DynamicTableEntity在过程中添加一列.以下是演示代码.

  var entity = new DynamicTableEntity("tomtest", "pk"); //PK, RK
  entity.Properties.Add("EndTime", new EntityProperty(DateTime.UtcNow));      //properties want to add    
  var mergeOperation = TableOperation.InsertOrMerge(entity);
  table.Execute(mergeOperation);
Run Code Online (Sandbox Code Playgroud)