持久存储到 Azure Table 存储时使用 POCO

Using POCOs when persisting to Azure Table Storage

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

已弃用的 azure-sdk-for-net 曾一度支持 POCO,但我在当前 WindowsAzure.Storage 中看不到这一点。

此处的最佳做法是什么?

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

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

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

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

我遇到了类似的问题并实现了一个通用对象 flattener/recomposer API 它将把你的复杂实体扁平化为扁平的 EntityProperty 字典并使它们可写到 Table存储,形式为DynamicTableEntity.

然后 API 将从 DynamicTableEntity.

EntityProperty 字典中重组整个复杂对象

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

我正在与 Azure 团队合作,将此 API 集成到 Azure 存储 SDK 中。您可以在此处查看拉取请求和代码:

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);

就这些:)

最新版本的 nuget 包还支持 IEnumerable、ICollection 等类型属性。

包的 .Net Core 版本在这里: https://www.nuget.org/packages/ObjectFlattenerRecomposer.Core/

CosmosDb Table api 版本的包在这里: https://www.nuget.org/packages/ObjectFlattenerRecomposer.CosmosDb.Table.Core/

我制作的库就是这样做的:

TableStorage.Abstractions.TableEntityConverters 将 POCO 转换为 DynamicTableEntity,反之亦然。它具有让您指定分区键、行键和忽略字段的功能。

TableStorage.Abstractions.POCO builds on top of this and a Table Storage repository library (TableStorage.Abstractions)。结合起来,它为您提供了一种使用 POCO 在 Table 存储上进行 CRUD 的非常简单的方法。