向 Azure Table 存储中的现有实体添加一列

Add a column to existing entity in Azure Table Storage

我正在 Azure Table 存储上的 table 中保存一些交易数据。当我尝试 "update" 我的 table 中的现有实体并向其添加新列时,看起来它没有添加该列。

这是一个示例:我正在 table 中节省时间 sheet 个条目。当我第一次创建实体时,有一个 StartTime 但没有 EndTime

PersonId -- TransactionId -- StartTime -- EndTime

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

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

虽然我不想存储任何虚拟数据。

Is there not a way to update an existing entity and add a column in the process?

是的,根据您的情况,我们可以通过两种方式做到这一点:编辑交易数据模型或使用 DynamicTableEntity

1.Edit 您的交易数据模型和设置结束时间日期时间和空值被接受。演示代码如下,

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

如果我们不将值分配给并尝试将实体插入 table,则没有 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);    

如何更新实体

 // 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);  

2.We 可以使用 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);

Azure Table 存储是一个 无架构 数据库,这意味着 table 中的实体实际上可以具有完全不同的列。

换句话说,您可以创建没有 EndTime 属性 的实体,如果不需要,并在以后通过 [= 添加 属性 10=] 操作,如果 EndTime 稍后变得必要。