Azure: How to save IDictionary<String> at TableStorage?

1.1k views Asked by At

I have a class with an IDictionary. The size of this object isn't fix to any particular size. The idea with this is to have a Dynamic Schema of my object. I want to store this object in the TableStorage. How can I do this? And how can I retrieve this information from store after this inside my object with the IDictionary again??

Thanks!!

3

There are 3 answers

0
Miguel On

You can use the Read and Write events from the TableStorageContext to perform this. You need to store the IDictionary content in other Field or as a BLOB file. In the Read event you create the IDictionary from the given field or retrive directly from the BLOB file. In the Write event you store the IDictionary to the field or as a BLOB file.

Important: The Write event occurs after the Entity traslation step then if you choose the field way you may need to write your changes directly to the XML serialization of the entity.

THIS sounds hard but is very useful in many scenarios

0
Igorek On

Dictionaries by default are not serializable. An object must be serializable in order to be saved to TableStorage. I suggest you use List or Array type of objects or write your own serializer for Dictionary if List or Arrays are not good enough for you.

0
Amit On

DynamicTableEntity takes IDictionary<string,EntityProperty> as a param.

This code executes in LinqPad:

void Main()
{
    var account = "";
    var key = "";
    var tableName = "";

    var storageAccount = GetStorageAccount(account, key);
    var cloudTableClient = storageAccount.CreateCloudTableClient();
    var table = cloudTableClient.GetTableReference(tableName);

    var partitionKey = "pk";
    var rowKey = "rk";

    //create the entity
    var entity = new DynamicTableEntity(partitionKey, rowKey, "*",
        new Dictionary<string, EntityProperty>{
                {"Prop1", new EntityProperty("stringVal")},
                {"Prop2", new EntityProperty(DateTimeOffset.UtcNow)},
            });

    //save the entity
    table.Execute(TableOperation.InsertOrReplace(entity));

    //retrieve the entity
    table.Execute(TableOperation.Retrieve(partitionKey, rowKey)).Result.Dump();
}

static CloudStorageAccount GetStorageAccount(string accountName, string key, bool useHttps = true)
{
    var storageCredentials = new StorageCredentials(accountName, key);
    var storageAccount = new CloudStorageAccount(storageCredentials, useHttps: useHttps);
    return storageAccount;
}