insert complex objects to azure table with TableServiceEntity

后端 未结 2 611
面向向阳花
面向向阳花 2021-02-05 21:14

I was considering adding a whole complex object into a table. Having come from good old fashioned SQL approach I\'d obviously separate this into tables but I\'m trying a differe

2条回答
  •  不知归路
    2021-02-05 22:14

    I have come across a similar problem and have implemented a generic object flattener/recomposer API that will flatten your complex entities into flat EntityProperty dictionaries and make them writeable to Table Storage, in the form of DynamicTableEntity.

    Same API will then recompose the entire complex object back from the EntityProperty dictionary of the DynamicTableEntity.

    Have a look at: https://www.nuget.org/packages/ObjectFlattenerRecomposer/

    Usage:

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

    Since then I worked with azure team and integrated this functionality to Azure Storage SDK version 8.0.

    One important note that api s in Azure SDK does NOT support IEnumerable or ICollection type properties. But if you get the nuget package v2 in the above link you can pretty much write any object into Azure Table Storage including objects with enumerable, collection type properties.

    https://msdn.microsoft.com/en-us/library/microsoft.windowsazure.storage.table.tableentity.flatten.aspx

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

    I also added TableEntityAdapter class to SDK version 8.2.0 to make the usage easier. Simply pass your complex entity to its constructor and it will transparently handle flattening/converting back your complex object on writes and reads. https://github.com/Azure/azure-storage-net/blob/master/Lib/Common/Table/TableEntityAdapter.cs

提交回复
热议问题