【问题标题】:Check if row exists with Azure Table Storage 1.8使用 Azure 表存储 1.8 检查行是否存在
【发布时间】:2013-01-18 19:03:38
【问题描述】:

Azure 表存储 .NET 客户端使用 SDK 1.8 进行了全面重新设计。使用新的 SDK,如何检查一行是否存在?

这是来自SDK's documentation 的示例,说明如何检索单个项目:

TableResult retrievedResult = table.Execute(retrieveOperation);

// Print the phone number of the result.
if (retrievedResult.Result != null)
   Console.WriteLine(((CustomerEntity)retrievedResult.Result).PhoneNumber);
else
   Console.WriteLine("The phone number could not be retrieved.");

根据示例,如果未找到任何行,retrievedResult.Result 应该为 null。但实际上并非如此,因为 table.Execute 会在没有找到任何行时抛出异常。

旧的 SDK 也是如此:如果未找到任何行,则会引发异常。但是有一个属性将其关闭:

TableServiceContext.IgnoreResourceNotFoundException = true

但是这个选项隐藏在新 SDK 的什么地方?

【问题讨论】:

    标签: .net azure azure-table-storage


    【解决方案1】:

    如果你使用TableEntity概念,你可以试试下面的代码:

            CloudTable table = cloudTableClient.GetTableReference(tableName);
            TableOperation retrieveOperation = TableOperation.Retrieve<YourEntity>(partitionKey, rowKey);
            TableResult retrievedResult = table.Execute(retrieveOperation);
            YourEntity fetchedEntity = retrievedResult.Result as YourEntity;
    

    如果实体不存在,你会得到 fetchedEntity 为 null。

    【讨论】:

    • 我认为这与文档中显示的代码相同。如果未找到该行,则 Execute 方法将引发异常。但似乎您可以设置“tableClient.GetTableServiceContext().IgnoreResourceNotFoundException = true”来获取空结果而不是异常。
    【解决方案2】:

    它在我的 SDK 1.8 中似乎一直在同一个位置,但它已经移到了存储 API 的 2.0 版本中。你用的是这个吗?

    Microsoft.WindowsAzure.StorageClient.TableServiceContext 已移至 Microsoft.WindowsAzure.Storage.Table.DataServices.TableServiceContext

    property you're looking for 似乎在那里仍然可用:)

    【讨论】:

    • 我觉得我对版本号有些困惑 :) 我使用的是 Azure Storage SDK 2.0,我认为它是 Azure SDK 1.8 的一部分。尽管如此,还是感谢您的帮助。我能够通过“tableClient.GetTableServiceContext().IgnoreResourceNotFoundException”找到该属性
    • 补充说明:随SDK分发的存储客户端库是2.0.0.0版本,存在一些bug。我建议从 Nuget 获取最新版本。截至今天,Nuget 上可用的最新版本是 2.0.3.0。
    猜你喜欢
    • 1970-01-01
    • 2011-02-08
    • 2014-06-06
    • 1970-01-01
    • 2017-04-02
    • 2017-03-06
    • 2013-07-05
    • 2014-08-13
    • 2017-11-02
    相关资源
    最近更新 更多