Azure Table存储(2)

今天我们继续接上一篇来谈一下Table存储。

以编程方式访问Table存储
获取组件

您可以使用NuGet来获取Microsoft.WindowsAzure.Storage.dll组件。 在Solution Explorer里右键点击你的Project, 然后选择Manage Nuget Packages, 在线搜索 “WindowsAzure.Storage” 然后点击安装Azure存储包和相关包。

Azure SDK .NET版也包含Microsoft.WindowsAzure.Storage.dll, 您可以在.NET k开发者中心拿到。 该组件安装在%Program Files%\Microsoft SDKs\Azure\.NET SDK\<sdk-version>\ref\ 目录下。

名字空间声明
把下面的代码加到你的C#程序的最上面以便于您访问Azure存储:

using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Table;

确保您引用Microsoft.WindowsAzure.Storage.dll组件

检索连接字符串
您可以使用CloudStorageAccount 类型来展示您的存储账户信息。 如果您使用Azure项目模板或者您有一个关于Microsoft.WindowsAzure.CloudConfigurationManager名字空间的引用, 您也可以是用CloudConfigurationManager 类型从Azure服务配置表来检索您的存储连接字符串和账户信息。

CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));

如果您的应用没有引用Microsoft.WindowsAzure.CloudConfigurationManager, 并且您的连接字符串存放在web.config或者app.config里, 那您就可以使用ConfigurationManager来获取连接字符串了。 不过您还需要添加一个对于System.Configuration.dll 的引用, 然后再添加一个命名空间的声明。

using System.Configuration;
...
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    ConfigurationManager.ConnectionStrings["StorageConnectionString"]); 

创建一个表Table
每个CloudTableClient 对象都可以让您拿到tables和entities的引用对象。 下面的代码新建了一个CloudTableClient 对象然后用它来创建一个Table

// Retrieve the storage account from the connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create the table client.
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

// Create the table if it doesn't exist.
CloudTable table = tableClient.GetTableReference("people");
table.CreateIfNotExists();

为Table创建一个entity

Entities使用TableEntity继承出来的一个自定义类来映射C# object. 为table添加一个entity, 需要创建一个类来定义你的entity的属性。 下面的代码使用客户的firstname和lastname作为rowkey和partitionkey来定义了一个entity。

public class CustomerEntity : TableEntity
{
    public CustomerEntity(string lastName, string firstName)
    {
        this.PartitionKey = lastName;
        this.RowKey = firstName;
    }

    public CustomerEntity() { }

    public string Email { get; set; }

    public string PhoneNumber { get; set; }
}

Table表与entity相关的操作使用的CloudTable 对象。 这个操作使用的是TableOperation 对象。下面的代码展示的是创建CloudTable 对象和CustomerEntity 对象。

// Retrieve the storage account from the connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
   CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create the table client.
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

// Create the CloudTable object that represents the "people" table.
CloudTable table = tableClient.GetTableReference("people");

// Create a new customer entity.
CustomerEntity customer1 = new CustomerEntity("Harp", "Walter");
customer1.Email = "Walter@contoso.com";
customer1.PhoneNumber = "425-555-0101";

// Create the TableOperation that inserts the customer entity.
TableOperation insertOperation = TableOperation.Insert(customer1);

// Execute the insert operation.
table.Execute(insertOperation);

批量添加entities
您可以通过一个写操作来批量天剑entities到一个Table里面。
1. 您可以在一个批量操作里包括更新, 删除和插入
2. 一个批量操作里面最多可以包括100 entities
3. 在一个批量操作的所有entities都必须使用相同的partition key
4. 如果是查询操作, 只能是批量操作里的一个唯一操作。

下面的代码使用了其中的TableBatchOperation Insert方法

// Retrieve the storage account from the connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create the table client.
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

// Create the CloudTable object that represents the "people" table.
CloudTable table = tableClient.GetTableReference("people");

// Create the batch operation.
TableBatchOperation batchOperation = new TableBatchOperation();

// Create a customer entity and add it to the table.
CustomerEntity customer1 = new CustomerEntity("Smith", "Jeff");
customer1.Email = "Jeff@contoso.com";
customer1.PhoneNumber = "425-555-0104";

// Create another customer entity and add it to the table.
CustomerEntity customer2 = new CustomerEntity("Smith", "Ben");
customer2.Email = "Ben@contoso.com";
customer2.PhoneNumber = "425-555-0102";

// Add both customer entities to the batch insert operation.
batchOperation.Insert(customer1);
batchOperation.Insert(customer2);

// Execute the batch operation.
table.ExecuteBatch(batchOperation);

在一个partition里面检索所有的entities
要完成这个操作, 您需要是用TableQuery 对象, 代码如下:

// Retrieve the storage account from the connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create the table client.
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

// Create the CloudTable object that represents the "people" table.
CloudTable table = tableClient.GetTableReference("people");

// Construct the query operation for all customer entities where PartitionKey="Smith".
TableQuery<CustomerEntity> query = new TableQuery<CustomerEntity>().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "Smith"));

// Print the fields for each customer.
foreach (CustomerEntity entity in table.ExecuteQuery(query))
{
    Console.WriteLine("{0}, {1}\t{2}\t{3}", entity.PartitionKey, entity.RowKey,
        entity.Email, entity.PhoneNumber);
}

在一个partition里面检索一系列的entities
如果您不是要检索所有的entities, 而是只需要其中的一部分, 请参照下面的代码

// Retrieve the storage account from the connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create the table client.
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

//Create the CloudTable object that represents the "people" table.
CloudTable table = tableClient.GetTableReference("people");

// Create the table query.
TableQuery<CustomerEntity> rangeQuery = new TableQuery<CustomerEntity>().Where(
    TableQuery.CombineFilters(
        TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "Smith"),
        TableOperators.And,
        TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.LessThan, "E")));

// Loop through the results, displaying information about the entity.
foreach (CustomerEntity entity in table.ExecuteQuery(rangeQuery))
{
    Console.WriteLine("{0}, {1}\t{2}\t{3}", entity.PartitionKey, entity.RowKey,
        entity.Email, entity.PhoneNumber);
}

检索一个单独的entity
您也可以单独检索一个entity, 示例代码如下:

/ Retrieve the storage account from the connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create the table client.
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

// Create the CloudTable object that represents the "people" table.
CloudTable table = tableClient.GetTableReference("people");

// Create a retrieve operation that takes a customer entity.
TableOperation retrieveOperation = TableOperation.Retrieve<CustomerEntity>("Smith", "Ben");

// Execute the retrieve operation.
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.");

替换一个entity
为了更新一个entity, 需要先从table服务里面拿到entity对象, 然后修改后保存回table服务。下面的代码实现修改现有客户的电话号码, 使用了Replace方法。

// Retrieve the storage account from the connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create the table client
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

// Create the CloudTable object that represents the "people" table.
CloudTable table = tableClient.GetTableReference("people");

// Create a retrieve operation that takes a customer entity.
TableOperation retrieveOperation = TableOperation.Retrieve<CustomerEntity>("Smith", "Ben");

// Execute the operation.
TableResult retrievedResult = table.Execute(retrieveOperation);

// Assign the result to a CustomerEntity object.
CustomerEntity updateEntity = (CustomerEntity)retrievedResult.Result;

if (updateEntity != null)
{
   // Change the phone number.
   updateEntity.PhoneNumber = "425-555-0105";

   // Create the InsertOrReplace TableOperation
   TableOperation updateOperation = TableOperation.Replace(updateEntity);

   // Execute the operation.
   table.Execute(updateOperation);

   Console.WriteLine("Entity updated.");
}

else
   Console.WriteLine("Entity could not be retrieved.");

Insert-or-replace一个entity
如果entity在从server调用后已经被修改过了, 则Replace会失败。 但是有时候你会不知道这个entity是否已经存在或者修改, 那这时候我们就可以使用InsertOrReplace

// Retrieve the storage account from the connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create the table client.
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

// Create the CloudTable object that represents the "people" table.
CloudTable table = tableClient.GetTableReference("people");

// Create a retrieve operation that takes a customer entity.
TableOperation retrieveOperation = TableOperation.Retrieve<CustomerEntity>("Smith", "Ben");

// Execute the operation.
TableResult retrievedResult = table.Execute(retrieveOperation);

// Assign the result to a CustomerEntity object.
CustomerEntity updateEntity = (CustomerEntity)retrievedResult.Result;

if (updateEntity != null)
{
   // Change the phone number.
   updateEntity.PhoneNumber = "425-555-1234";

   // Create the InsertOrReplace TableOperation
   TableOperation insertOrReplaceOperation = TableOperation.InsertOrReplace(updateEntity);

   // Execute the operation.
   table.Execute(insertOrReplaceOperation);

   Console.WriteLine("Entity was updated.");
}

else
   Console.WriteLine("Entity could not be retrieved.");

查询entity属性的子集
示例代码如下:

// Retrieve storage account from connection string
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create the table client
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

//Create the CloudTable that represents the "people" table.
CloudTable table = tableClient.GetTableReference("people");

// Define the query, and only select the Email property
TableQuery<DynamicTableEntity> projectionQuery = new TableQuery<DynamicTableEntity>().Select(new string[] { "Email" });

// Define an entity resolver to work with the entity after retrieval.
EntityResolver<string> resolver = (pk, rk, ts, props, etag) => props.ContainsKey("Email") ? props["Email"].StringValue : null;

foreach (string projectedEmail in table.ExecuteQuery(projectionQuery, resolver, null, null))
{
    Console.WriteLine(projectedEmail);
}

删除一个entity
你可以在接收到一个entity之后轻松的删除它。

// Retrieve storage account from connection string
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create the table client
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

//Create the CloudTable that represents the "people" table.
CloudTable table = tableClient.GetTableReference("people");

// Create a retrieve operation that expects a customer entity.
TableOperation retrieveOperation = TableOperation.Retrieve<CustomerEntity>("Smith", "Ben");

// Execute the operation.
TableResult retrievedResult = table.Execute(retrieveOperation);

// Assign the result to a CustomerEntity.
CustomerEntity deleteEntity = (CustomerEntity)retrievedResult.Result;

// Create the Delete TableOperation.
if (deleteEntity != null)
{
   TableOperation deleteOperation = TableOperation.Delete(deleteEntity);

   // Execute the operation.
   table.Execute(deleteOperation);

   Console.WriteLine("Entity deleted.");
}

else
   Console.WriteLine("Could not retrieve the entity.");

删除一个Table
示例代码如下

// Retrieve the storage account from the connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create the table client.
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

//Create the CloudTable that represents the "people" table.
CloudTable table = tableClient.GetTableReference("people");

// Delete the table it if exists.
table.DeleteIfExists();

异步方式接收entities
您如果需要读取以大批entities, 而且您想实时得的结果, 那您可以使用异步的方式。 示例代码如下:

// Initialize a default TableQuery to retrieve all the entities in the table
TableQuery tableQuery = new TableQuery();

// Initialize the continuation token to null to start from the beginning of the table
TableContinuationToken continuationToken = null;

do
{
    // Retrieve a segment (up to 1000 entities)
    TableQuerySegment<CustomerEntity> tableQueryResult =
        await table.ExecuteQuerySegmentedAsync(tableQuery, continuationToken);

    // Assign the new continuation token to tell the service where to
    // continue on the next iteration (or null if it has reached the end)
    continuationToken = tableQueryResult.ContinuationToken;

    // Print the number of rows retrieved
    Console.WriteLine("Rows retrieved {0}", tableQueryResult.Results.Count);

// Loop until a null continuation token is received indicating the end of the table
} while(continuationToken != null);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值