【发布时间】:2010-11-28 18:35:19
【问题描述】:
我有一个带有 IDictionary 的课程。此对象的大小不固定为任何特定大小。这样做的想法是拥有我的对象的 Dynamic Schema。我想将此对象存储在 TableStorage 中。我怎样才能做到这一点?以及如何在我的对象内部再次使用 IDictionary 从存储中检索此信息??
谢谢!!
【问题讨论】:
标签: c# .net azure azure-table-storage dynamic-schema
我有一个带有 IDictionary 的课程。此对象的大小不固定为任何特定大小。这样做的想法是拥有我的对象的 Dynamic Schema。我想将此对象存储在 TableStorage 中。我怎样才能做到这一点?以及如何在我的对象内部再次使用 IDictionary 从存储中检索此信息??
谢谢!!
【问题讨论】:
标签: c# .net azure azure-table-storage dynamic-schema
DynamicTableEntity 将IDictionary<string,EntityProperty> 作为参数。
这段代码在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;
}
【讨论】:
字典默认是不可序列化的。对象必须可序列化才能保存到 TableStorage。我建议您使用 List 或 Array 类型的对象,或者如果 List 或 Arrays 对您来说不够好,请为 Dictionary 编写您自己的序列化程序。
【讨论】:
您可以使用 TableStorageContext 中的读取和写入事件来执行此操作。您需要将 IDictionary 内容存储在其他字段中或作为 BLOB 文件。在读取事件中,您从给定字段创建 IDictionary 或直接从 BLOB 文件中检索。在 Write 事件中,您将 IDictionary 存储到字段或作为 BLOB 文件。
重要提示:Write 事件发生在实体转换步骤之后,如果您选择字段方式,您可能需要将更改直接写入实体的 XML 序列化。
这听起来很难,但在许多情况下都非常有用
【讨论】: