Azure表存储升级

时间:2014-10-10 08:40:56

标签: azure azure-storage azure-table-storage

我有一个带有以下实体的Azure表存储:

SampleEntity : TableEntity
{
  public int EmployeeId{get; set;}
}

我已经在表格中插入了100条记录。 现在我对EmployeeID应该是字符串的要求进行了更改。此外,我不应删除已插入的现有100条记录。 因此,我按如下方式更改了现有的SampleEntity:

SampleEntity : TableEntity
{
  public string EmployeeId{get; set;}
}

我已经将EmployeeId作为字符串插入到表中的50行。

现在,当我使用新的SampleEntity(使用字符串EmployeeID)对表执行GetOperation时,我得到150行,但使用旧SampleEntity插入的前100行的EmployeeID值为 0

另一方面,如果我切换到旧的SampleEntity并执行GetOperaiton,我会为使用新SampleEntity插入的50行的EmployeeID获取空值。

如何使用新的示例实体在字符串中使用EmployeeId的值来覆盖所有150行?

1 个答案:

答案 0 :(得分:3)

您可能要做的是将Integer类型EmployeeId的数据类型更改为String。为此,您需要做的是将所有实体获取为DynamicTableEntity并检查EmployeeId属性的属性类型。如果类型为Int32,您将创建一个具有String类型EmployeeId属性的新实体,并将其值设置为旧实体的EmployeeId值,然后更新现有实体(您将保持相同的PartitionKeyRowKey)。

请参阅下面的示例代码,例如:

        //Get all entities and make sure we get them as dynamic table entity.
        var query = new TableQuery();
        var allEntities = table.ExecuteQuery(query);
        foreach (var entity in allEntities)
        {
            var propertyType = entity.Properties["EmployeeId"].PropertyType;
            if (propertyType == EdmType.Int32 && entity.Properties["EmployeeId"].Int32Value.HasValue)
            {
                //This is an entity with Integer type EmployeeId. What we need to do is update this entity with a new entity where data type of EmployeeId is String.
                var employeeId = entity.Properties["EmployeeId"].Int32Value.Value;
                var newEntityWithStringType = new DynamicTableEntity()
                {
                    PartitionKey = entity.PartitionKey,
                    RowKey = entity.RowKey,
                    ETag = "*"
                };
                newEntityWithStringType.Properties.Add("EmployeeId", new EntityProperty(employeeId.ToString()));
                TableOperation updateOperation = TableOperation.Replace(newEntityWithStringType);
                table.Execute(updateOperation);
            }
        }

上面的代码假设您只有一个属性EmployeeId。如果有更多属性,请确保将它们包含在newEntityWithStringType属性中。