c# - 给定 PartitionKey、RowKey、属性名称和值,如何更新该实体的属性值?

标签 c# azure azure-table-storage

使用 Azure 表,如果我知道实体的 RowKey 和 PartitionKey(以便我可以检索该实体),如何编辑该实体的特定属性值?

这听起来像是一个非常标准的操作,但正常的做法是这样的:

public void UpdateEntity(ITableEntity entity)
{
    TableOperation replaceOperation = TableOperation.Replace(entity);
    table.Execute(replaceOperation);
}

即给出整个 C# TableEntity 对象作为替换,而不是单个属性名称/值对。

我想要更多类似的东西:

public void UpdateEntityProperty<T>(string partitionKey, string rowKey,
                                string propertyName, T newPropertyValue)
{
    TableOperation retrieveOperation = TableOperation.Retrieve(partitionKey, rowKey);
    TableResult retrievedResult = table.Execute(retrieveOperation);
    TableEntity entity = (TableEntity)retrievedResult.Result;

    // This  line, of course, doesn't compile. But you get the idea.
    entity.SetPropertyValue(propertyName, newPropertyValue);

    TableOperation replaceOperation = TableOperation.Replace(entity);
    table.Execute(replaceOperation);
}

我的理解是,在幕后,行存储为与该行上的属性相对应的一组键值对,因此更新属性的值应该很容易,而无需定义从 TableEntity 派生的整个 C# 类这样做。

我该怎么做?

最佳答案

为了完整起见,以下是我最终使用的内容,灵感来自 Gaurav Mantri 的答案:

public void UpdateEntityProperty(string partitionKey, string rowKey,
                                 string propertyName, string newPropertyValue)
{
    var entity = new DynamicTableEntity(partitionKey, rowKey);
    var properties = new Dictionary<string, EntityProperty>();
    properties.Add(propertyName, new EntityProperty(newPropertyValue));
    var mergeOperation = TableOperation.Merge(entity);
    table.Execute(mergeOperation);
}

关于c# - 给定 PartitionKey、RowKey、属性名称和值,如何更新该实体的属性值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14732429/

相关文章:

azure - 如何修复 "Destination URL, which is treated as Reply URL for enabling Microsoft Azure Authentication, is missing"

azure - 编写 Azure 表存储 - 本地和云的不同行为

c# - OSX 上的 Visual Studio Code 如何导入 sln/csproj 并运行?

c# - 跨表分区的事务性插入

c# - 如何将参数传递给Azure函数

c# - 使用 DateTimeOffset 更新 Azure 表 TableEntity 会引发 NotImplemented 异常

c# - 如何在C#中获取Azure表存储中的所有行?

C# 任务不会被取消

c# - 如何在 winform 上刷新数据驱动的组合框

c# - 获取当前值和先前值