假设我有多个从 TableEntity 继承的实体。
我想使用一个通用类,比如 Cachemanager ,并写入不同的 T 天蓝色存储
下面的这个链接提到了 TableEntityAdapter
我正在寻找代码示例。谢谢,彼得
我写了 TableEntityAdapter 类,所以我会尝试提供使用示例,虽然我看到一个月前有人问过问题,但希望它仍然有用。
首先看一下SDK的单元测试是如何测试的:https : //github.com/Azure/azure-storage-net/blob/master/Test/ClassLibraryCommon/Table/TableOperationUnitTests.cs
搜索 TableEntityAdapter 以找到相关测试。 请注意,单元测试当然不会写入实际的表存储服务,它们模拟了在 api 调用方面读写时会发生的情况,但它们应该给你一个好主意。
您原来的 ShapeEntity 对象甚至不需要实现 ITableEntity 接口。它还可以包含复杂的嵌套属性。TableEntityAdapter类支持这些场景。
下面是一个简化的示例代码TableEntityAdapter:
要将自定义 .Net 对象写入表存储:
// 1. ShapeEntity is the custom .Net object that we want to write and read from Table Storage.
ShapeEntity shapeEntity = new ShapeEntity(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "square", 4, 4);
OperationContext operationContext = new OperationContext();
// 2. Instantiate a TableEntityAdapter object, passing in the custom object to its constructor. Internally this instance will keep a reference to our custom ShapeEntity object.
TableEntityAdapter<ShapeEntity> writeToTableStorage = new TableEntityAdapter<ShapeEntity>(shapeEntity, partitionKey, rowKey);
// 3. Now you can write the writeToTableStorage object to Table Storage just like any other object which inherits from ITableEntity interface. The TableAdapter generic class handles the boiler plate code and hand shaking between your custom .Net object and table storage sdk / service.
To read your custom object from Table Storage:
// 1. Read your entity back from table storage using the same partition / row key you specified (see step 2 above). You can use the Retrieve<T> table operation, specify T as TableEntityAdapter<ShapeEntity>
// 2. This should return you the TableEntityAdapter<ShapeEntity> object that you wrote to TableStorage at step 3 above.
// 3. To access the original ShapeEntity object, just refer to the OriginalEntity property of the returned TableEntityAdapter<ShapeEntity> object.
Run Code Online (Sandbox Code Playgroud)
您原来的 ShapeEntity 对象甚至不需要实现 ITableEntity 接口。它还可以包含复杂的嵌套属性。TableEntityAdapter 类支持这些场景。
注意: TableEntityAdapter api 不支持具有集合类型属性的对象,即。List,Array,IEnumerable,ICollection等。
如果您的对象包含这些类型的属性(直接在根下或其对象图中的某处),那么您应该考虑使用我编写的原始 Nuget 包,它也支持集合类型属性类型。
ObjectFlattenerRecomposer支持 Collection、Enumerable 类型属性的 Api 2.0 版:https :
//www.nuget.org/packages/ObjectFlattenerRecomposer/
和最近上传的 .Net Core 版本:https : //www.nuget.org/packages/ObjectFlattenerRecomposer.Core/1.0.0/