使用 C# 处理 Azure 存储表





5.00/5 (3投票s)
本文演示了如何创建新的 Azure 存储表并对该表执行 CRUD 操作。
引言
Azure 表存储是一种 No SQL 键属性数据存储。 这有助于存储大量结构化数据(以太字节为单位),这些数据没有复杂的关系且是无模式的。 存储的数据是持久的、高度可扩展的,并且可以快速检索。 本文演示了如何使用 C# 编程创建一个新的 Azure 存储表,对该表执行 CRUD 操作(读取、插入、更新和删除数据)并删除创建的表。
背景
表存储数据存储在跨多个存储节点的分区中。 存储的每个数据实体都与一个行键、一个分区键和一个时间戳相关联。 每个分区都由一个分区键标识。 在一个分区中,每个数据实体都与一个行键相关联。 分区键和行键的组合唯一地标识一个数据实体。 与数据实体关联的时间戳跟踪数据实体上次修改的时间。 行键和分区键可以由开发人员修改。 时间戳由服务器管理,不能由开发人员修改。
Using the Code
使用 Visual Studio 2015 创建控制台应用程序,以演示本文中的表存储操作。 Windows Azure 存储 SDK 从 Nuget 包管理器安装在控制台应用程序中
创建客户实体
创建数据实体类 Customer。 此实体数据将保存到表存储。Customer
类派生自 TableEntity
类,该类位于 Microsoft.WindowsAzure.Storage.Table
命名空间中。 表存储中的每个实体数据都必须与一个分区键和一个行键相关联。 AssignPartitionKey
方法将客户类型分配为分区键,而 AssignRowKey
方法将客户 ID 分配为行键。
class Customer:TableEntity
{
private int customerID;
private string customerName;
private string customerDetails;
private string customerType;
public void AssignRowKey()
{
this.RowKey = customerID.ToString();
}
public void AssignPartitionKey()
{
this.PartitionKey = customerType;
}
public int CustomerID
{
get
{
return customerID;
}
set
{
customerID = value;
}
}
public string CustomerName
{
get
{
return customerName;
}
set
{
customerName = value;
}
}
public string CustomerDetails
{
get
{
return customerDetails;
}
set
{
customerDetails = value;
}
}
public string CustomerType
{
get
{
return customerType;
}
set
{
customerType = value;
}
}
}
将连接字符串添加到配置文件
表存储的连接字符串包含存储帐户名称和存储帐户的访问密钥,这些密钥可以从 Azure 门户中获取。
<add key="StorageConnectionString" value="DefaultEndpointsProtocol=https;
AccountName=[Name of storage account];AccountKey=[Access Key for storage account]">
创建一个表
CloudStorageAccount.Parse
方法解析连接字符串并返回一个云存储帐户对象。 可以使用 CloudTableClient
类访问存储在表存储中的表和实体。 GetTableReference
方法将表名作为参数,并返回对云表的引用。 CreateIfNotExists
方法在表不存在时创建一个新表。
CloudStorageAccount cloudStorageAccount =
CloudStorageAccount.Parse
(ConfigurationManager.AppSettings["StorageConnectionString"]);
CloudTableClient tableClient = cloudStorageAccount.CreateCloudTableClient();
Console.WriteLine("Enter Table Name to create");
string tableName = Console.ReadLine();
CloudTable cloudTable = tableClient.GetTableReference(tableName);
CreateNewTable(cloudTable);
public static void CreateNewTable(CloudTable table)
{
if (!table.CreateIfNotExists())
{
Console.WriteLine("Table {0} already exists", table.Name);
return;
}
Console.WriteLine("Table {0} created", table.Name);
}
插入和更新数据
TableOperation.Insert
方法将 customer
实体作为输入,并返回必须针对表执行的 TableOperation
对象。 RetrieveRecord
方法搜索并获取正在插入的客户实体数据。 如果存在相同的客户数据实体,则不应发生 insert
。 通过调用 customer
实体类中的 AssignPartitionKey
和 AssignRowKey
方法来分配数据记录的行键和分区键是分区的。
public static void InsertRecordToTable(CloudTable table)
{
Console.WriteLine("Enter customer type");
string customerType = Console.ReadLine();
Console.WriteLine("Enter customer ID");
string customerID = Console.ReadLine();
Console.WriteLine("Enter customer name");
string customerName = Console.ReadLine();
Console.WriteLine("Enter customer details");
string customerDetails = Console.ReadLine();
Customer customerEntity = new Customer();
customerEntity.CustomerType = customerType;
customerEntity.CustomerID = Int32.Parse(customerID);
customerEntity.CustomerDetails = customerDetails;
customerEntity.CustomerName = customerName;
customerEntity.AssignPartitionKey();
customerEntity.AssignRowKey();
Customer custEntity = RetrieveRecord(table, customerType, customerID);
if (custEntity == null)
{
TableOperation tableOperation = TableOperation.Insert(customerEntity);
table.Execute(tableOperation);
Console.WriteLine("Record inserted");
}
else
{
Console.WriteLine("Record exists");
}
}
RetrieveRecord
查询表并返回与所查询的行键和分区键匹配的 customer
实体。
public static Customer RetrieveRecord(CloudTable table,string partitionKey,string rowKey)
{
TableOperation tableOperation = TableOperation.Retrieve<Customer>(partitionKey, rowKey);
TableResult tableResult = table.Execute(tableOperation);
return tableResult.Result as Customer;
}
实体记录由分区键和行键组合唯一标识。 在更新记录之前,使用 RetrieveRecord
方法通过传递分区键和行键作为参数在表中搜索它。 如果实体存在,则仅执行更新操作。 TableOperation.Replace
方法执行更新操作。
public static void UpdateRecordInTable(CloudTable table)
{
Console.WriteLine("Enter customer type");
string customerType = Console.ReadLine();
Console.WriteLine("Enter customer ID");
string customerID = Console.ReadLine();
Console.WriteLine("Enter customer name");
string customerName = Console.ReadLine();
Console.WriteLine("Enter customer details");
string customerDetails = Console.ReadLine();
Customer customerEntity = RetrieveRecord(table, customerType, customerID);
if (customerEntity != null)
{
customerEntity.CustomerDetails = customerDetails;
customerEntity.CustomerName = customerName;
TableOperation tableOperation = TableOperation.Replace(customerEntity);
table.Execute(tableOperation);
Console.WriteLine("Record updated");
}
else
{
Console.WriteLine("Record does not exists");
}
}
显示存储在表中的所有数据
创建 TableQuery
对象并使用 ExecuteQuery
针对表执行该对象。
public static void DisplayTableRecords(CloudTable table)
{
TableQuery<Customer> tableQuery = new TableQuery<Customer>();
foreach (Customer customerEntity in table.ExecuteQuery(tableQuery))
{
Console.WriteLine("Customer ID : {0}", customerEntity.CustomerID);
Console.WriteLine("Customer Type : {0}", customerEntity.CustomerType);
Console.WriteLine("Customer Name : {0}", customerEntity.CustomerName);
Console.WriteLine("Customer Details : {0}", customerEntity.CustomerDetails);
Console.WriteLine("******************************");
}
}
从表中删除数据并删除表
TableOperation.Delete
创建必须针对表执行的表删除操作对象。 要删除的记录由行键和分区键标识。 如果记录存在,则仅删除它。
public static void DeleteRecordinTable(CloudTable table)
{
Console.WriteLine("Enter customer type");
string customerType = Console.ReadLine();
Console.WriteLine("Enter customer ID");
string customerID = Console.ReadLine();
Customer customerEntity = RetrieveRecord(table, customerType, customerID);
if (customerEntity != null)
{
TableOperation tableOperation = TableOperation.Delete(customerEntity);
table.Execute(tableOperation);
Console.WriteLine("Record deleted");
}
else
{
Console.WriteLine("Record does not exists");
}
}
DeleteIfExists
方法删除表存储中存在的表。
public static void DropTable(CloudTable table)
{
if (!table.DeleteIfExists())
{
Console.WriteLine("Table does not exists");
}
}
关注点
本文附有示例代码。 解决方案是使用 Visual Studio 2015 社区版开发的。 要试用示例,必须在配置文件中指定正确的 Azure 存储帐户名称和访问密钥。 确保在连接到互联网时构建解决方案,以便还原 nuget 包。