Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given a PartitionKey, RowKey, Property name and value, how do I update that entity's property value?

With azure tables, if I know an entity's RowKey and PartitionKey (so I can retrieve that entity), how do I edit a particular property value on that entity?

This sounds like a pretty standard operation to do, but the normal way of doing it is something like:

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

i.e. a whole C# TableEntity object is given as a replacement, rather than an individual property name/value pair.

I want something more like:

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

My understanding is that behind the scenes, the rows are stored as a set of key-value pairs corresponding to properties on that row, so updating a property's value should be easy without having to define a whole C# class deriving from TableEntity to do so.

How would I do this?

like image 638
George Powell Avatar asked Dec 01 '22 22:12

George Powell


1 Answers

Just for completeness, here's what I ended up using, inspired by Gaurav Mantri's answer:

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);
}
like image 87
George Powell Avatar answered Dec 05 '22 08:12

George Powell