持久保存到Azure表存储时使用POCO
我打算在我的ASP.NET 5(MVC 6)应用程序中使用Azure表存储,并添加了WindowsAzure.Storage
NuGet包,但当我注意到所有我需要的模型都需要从Microsoft.WindowsAzure.Storage.Table.TableEntity
inheritance时,我感到非常失望.WindowsAzure Microsoft.WindowsAzure.Storage.Table.TableEntity
。 现在我认为最好的解决方案是拥有两组实体并在我的主域对象和用于持久存储到表存储的实体对象之间创建映射。 我不想将WindowsAzure.Storage
包添加到我的所有项目中。
弃用的azure-sdk-for-net在某一点上得到了对POCO的支持,但我在目前的WindowsAzure.Storage中没有看到这一点。
这里的最佳做法是什么?
您可以远离inheritanceTableEntity,但为此您最终会编写一些映射代码。 在实际与Table Storage交互的代码中,您可以使用DynamicTableEntity
从更多原始表数据到对象进行一些映射,以完全控制序列化。
有几篇文章可以帮助你:
- Azure EntityAdapter具有不受支持的表类型
- 使用EntityAdapter进行Azure表存储
- 使用EntityAdapter在Azure表存储中使用DTO / POCO
如果查看第二篇文章,它会显示在Azure表存储中保存和更新的特定POCO对象的代码。 第三篇文章扩展了第一篇包含ETag支持的工作。
您没有详细说明尝试写入Azure表存储的实体类型,但是如果您的实体包含嵌套的复杂属性,并且您要编写包含复杂嵌套属性的整个对象图(它们本身可能包含嵌套属性) ,这些建议的解决方案都不起作用。
我遇到了类似的问题,并实现了一个通用的对象flattener / recomposer API,它将复杂的实体展平为扁平的EntityProperty
词典,并以DynamicTableEntity
的forms将它们写入Table Storage。
然后,相同的API将从DynamicTableEntity
的EntityProperty
字典重新组合整个复杂对象。
请查看: 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 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(entity.Properties);
就这样 :)
对此进行了更新,我已将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中的方法。