我有一個類IDictionary。此對象的大小不適用於任何特定的大小。這個想法是我的對象有一個動態模式。我想將這個對象存儲在TableStorage中。我怎樣才能做到這一點?我怎麼才能從商店檢索這個信息後,在我的對象與IDictionary再次?Azure:如何在TableStorage上保存IDictionary <String>?
謝謝!
我有一個類IDictionary。此對象的大小不適用於任何特定的大小。這個想法是我的對象有一個動態模式。我想將這個對象存儲在TableStorage中。我怎樣才能做到這一點?我怎麼才能從商店檢索這個信息後,在我的對象與IDictionary再次?Azure:如何在TableStorage上保存IDictionary <String>?
謝謝!
詞典默認情況下不可序列化。一個對象必須是可序列化的才能保存到TableStorage。我建議你使用List或Array類型的對象,或者如果List或Arrays對你來說不夠好,你可以編寫你自己的字典序列化程序。
您可以使用TableStorageContext中的讀取和寫入事件來執行此操作。您需要將IDictionary內容存儲在其他字段中或作爲BLOB文件。在Read事件中,您可以從給定字段創建IDictionary或直接從BLOB文件進行回放。在Write事件中,您將IDictionary存儲到該字段或作爲BLOB文件。
重要事項:Write事件發生在實體描述步驟之後,如果選擇字段方式,您可能需要將更改直接寫入實體的XML序列化。
這聽起來很難,但非常有用的在許多情況下
DynamicTableEntity
需要IDictionary<string,EntityProperty>
作爲PARAM。
此代碼執行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;
}