我有一个类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;
}