持久保存到Azure表存储时使用POCO

hen*_*gst 8 c# asp.net azure azure-table-storage asp.net-core

我打算在我的ASP.NET 5(MVC 6)应用程序中使用Azure表存储并添加了WindowsAzure.StorageNuGet包,但是当我注意到我所有的entant模型都需要继承时,我真的很失望Microsoft.WindowsAzure.Storage.Table.TableEntity.现在我认为最好的解决方案是拥有两组实体并在我的主域对象和用于持久存储到表存储的实体对象之间创建映射.我不想将WindowsAzure.Storage包添加到我的所有项目中.

弃用的azure-sdk-for-net在某一点上得到了对POCO的支持,但我在目前的WindowsAzure.Storage中没有看到这一点.

这里的最佳做法是什么?

Dog*_*lan 7

您没有详细说明尝试写入Azure表存储的实体类型,但是如果您的实体包含嵌套的复杂属性,并且您要编写整个对象图,包括复杂的嵌套属性(它们本身可能包含嵌套属性) ,这些建议的解决方案都不起作用.

我遇到了类似的问题,并实现了一个通用的对象flattener/recomposer API,它将复杂的实体扁平化为扁平EntityProperty字典,并以表格形式将它们写入Table Storage DynamicTableEntity.

然后,相同的API将从EntityProperty字典中重新组合整个复杂对象DynamicTableEntity.

看看:https://www.nuget.org/packages/ObjectFlattenerRecomposer/

我正在与Azure团队合作,将此API集成到Azure Storage SDK中.您可以在这里查看pull请求和代码:

https://github.com/Azure/azure-storage-net/pull/337/commits

用法:

//Flatten object of type Order) and convert it to EntityProperty Dictionary
 Dictionary<string, EntityProperty> flattenedProperties = EntityPropertyConverter.Flatten(order);

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

// Write the DynamicTableEntity 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.
 Order order = EntityPropertyConverter.ConvertBack<Order>(entity.Properties);
Run Code Online (Sandbox Code Playgroud)

就这样 :)

对此进行了更新,我已将ObjectFlattenerRecomposer API集成到Azure Storage SDK 8.0.0版中

Flatten和ConvertBack方法通过SDK的TableEntity类作为静态方法公开提供.请参阅下面的msdn文档:

https://msdn.microsoft.com/en-us/library/azure/mt775434.aspx

https://msdn.microsoft.com/en-us/library/azure/mt775432.aspx

因此,如果您获得Azure Storage .Net SDK 8.0.0或更高版本,则可以直接使用存储SDK中的方法.


Mik*_*eWo 3

您可以摆脱从 TableEntity 继承,但这样做最终需要编写一些映射代码。在实际与表存储交互的代码中,您可以使用DynamicTableEntity完全控制序列化来进行从更多原始表数据到对象的映射。

有几篇文章可能会对您有所帮助:

如果您查看第二篇文章,它会显示在 Azure 表存储中保存和更新的特定 POCO 对象的代码。第三篇文章扩展了第一篇文章的工作,包括 ETag 支持。