非派生POCO和Azure存储

时间:2013-03-28 15:12:49

标签: azure-table-storage

是否可以为Azure表存储提供非派生POCO?

换句话说,POCO并非来自TableEntity或实施ITableEntity

似乎需要有一个依赖于接口或基类的模型,因为这会导致链中的引用泄漏 - 我不能在不知道Azure的情况下在另一个层中设置模型存储接口或基类!

3 个答案:

答案 0 :(得分:8)

看看DynamicTableEntity(ctrl + f)。它可用于查询和插入实体。

使用此类型,您不会在域模型中引入任何依赖项,但是您必须自己将POCO转换为DynamicTableEntity - 如果您愿意使用POCO标记您的POCO,则可以轻松自动执行此过程一个自定义界面并编写一个mapper(基本上你只需要一个属性字典+需要知道它们是Partition / RowKey)。

您不能只在Azure表存储中保存任何实体的原因是它需要知道哪个属性充当分区键,哪个属性作为行键。必须在“较低级别”使用DynamicTableEntity的好处是,您可以创建仅返回属性子集的查询,从而减少资源消耗。在您的情况下,这可能有用也可能没有用。

答案 1 :(得分:0)

看看我实现的包并放入Nuget: https://www.nuget.org/packages/ObjectFlattenerRecomposer/

它也被添加到Azure Storage SDK的下一个版本中: https://github.com/Azure/azure-storage-net/pull/337/files

说明

提供将复杂对象展平为EntityProperty字典的功能,以及从展平属性字典中重构原始复杂对象的功能。一种用法是API允许将具有嵌套属性的任何复杂对象以平面形式写入Azure表存储,这通常不可能使用Azure存储客户端SDK。

2.0版现在还支持编写和读取IEnumerable类型属性,如列表,数组,字典到Azure表存储。

博客:https://doguarslan.wordpress.com/2016/02/03/writing-complex-objects-to-azure-table-storage/

用法:

//Flatten object and convert it to EntityProperty Dictionary

Dictionary<string, EntityProperty> flattenedProperties = ObjectFlattenerRecomposer.Flatten(complexObject);

// Create a DynamicTableEntity and set its PK and RK
DynamicTableEntity dynamicTableEntity = new DynamicTableEntity(partitionKey, rowKey);

dynamicTableEntity.Properties = flattenedProperties;

// Write the DynammicTableEntity to Azure Table Storage using client SDK

//Read the entity back from AzureTableStorage as DynamicTableEntity using the same PK and RK
DynamicTableEntity entity = [Read from Azure using the PK and RK];

//Convert the DynamicTableEntity back to original complex object.
Imagine original complexObject was of type Order.

Order order = ObjectFlattenerRecomposer.ConvertBack<Order>(entity.Properties);

答案 2 :(得分:-1)

首先,还有TableEntity和ITableEntity的另一种替代方法,即使用DataServiceKey属性来装饰您的类,如下例所示:

[DataServiceKey("PartitionKey", "RowKey")]
public class MyEntity
{
    public string PartitionKey {get; set;}
    public string RowKey {get; set;}
    public DateTime Timestamp {get; set;}
    //other properties
}

但是,这并不能真正解决您不希望将Azure实现泄漏到模型类中的问题。在这种情况下,我认为您可能希望使用像LOKAD Fat Entities这样的包装器实现。 Lokad将处理模型对象的序列化/反序列化为包装器,而包装器又存储在表存储器中。然而,Lokad的一个缺点是,您的对象在存储中变得不透明,您无法使用Azure Storage Explorer之类的东西浏览它们。