为什么 Azure 表存储在使用解析名称时不保留类型名称

本文关键字:类型 保留 Azure 存储 为什么 | 更新日期: 2023-09-27 18:34:52

我试图控制 Azure 表实体的

序列化,作为如何使用对 Azure 表存储的单个查询检索多种类型的实体的后续操作? 并且遇到了(对我来说(意外行为。

检索

项目时,无论我在保存实体时将其设置为什么,名称始终是" <myaccountname>.Pets "。为什么不保留字体名称?

根据MSDN:

DataServiceContext.ResolveType

获取或设置一个函数,该函数用于在从开放数据协议 (OData( 服务接收实体时重写客户端库使用的默认类型解析选项。

DataServiceContext.ResolveName

获取或设置一个函数,以便在将实体发送到数据服务时重写客户端库使用的默认类型解析策略。

而这个博客条目不应该是这样。

这是一个简单的测试:

public class Pet : TableServiceEntity { }
    public class Cat : Pet { }
    public class Dog : Pet { }

    public class Test
    { 
        public void RunTest()
        {
            //this.Create();
            this.Read();
        }
        public TableServiceContext GetTableServiceContext()
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("StorageConnectionString"));
            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
            tableClient.CreateTableIfNotExist("Pets");
            TableServiceContext serviceContext = tableClient.GetDataServiceContext();
            serviceContext.ResolveName = (entityType) =>
            {
                return entityType.FullName;
            };
            serviceContext.ResolveType = (s) =>
            {
                return Type.GetType(s);
            };
            return serviceContext;
        }
        public void Create()
        {
            var serviceContext = this.GetTableServiceContext();
            // Create entries
            var cat = new Cat() { PartitionKey = "cats", RowKey = "1" };
            serviceContext.AddObject("Pets", cat);
            var dog = new Dog() { PartitionKey = "dogs", RowKey = "1" };
            serviceContext.AddObject("Pets", dog);

            serviceContext.SaveChangesWithRetries();
        }
        public void Read()
        {
            var serviceContext = this.GetTableServiceContext();
            var pets = serviceContext.CreateQuery<Pet>("Pets").AsTableServiceQuery<Pet>().ToArray();
            foreach (var pet in pets)
            {
                Console.WriteLine(pet.GetType());
            }
        }
    }

为什么 Azure 表存储在使用解析名称时不保留类型名称

经过一些挖掘和讨论,我发现 azure 表(无架构(从未看到过该类型名。相反,所有公共属性都是序列化的,只需将属性的有效负载发送到服务。

如果需要确定类型,则需要在有效负载中存储/检查属性。这可以通过读取/写入实体事件来完成。

您的目标是一次返回异类集合,还是将其限制为仅一种类型。如果是后者,那么最好将类型存储在主键中,如果可能的话,行键,或者存储在单独的字段中并基于此进行查询。