上一篇文章我們談到了 建立
Table,InsertOrReplace 資料,讀取資料 ,這一篇文章我們來聊一下關於刪除資料,還有更改資料使用 Etag
1. 刪除資料 ,其實也沒什麼特別的,直接提供 PartitionKey 還有 RowKey 刪除即可以
var connectionString = "your_connection_string";
var tableName = "USERSAMPLE";
var CSAccount = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(connectionString);
var CTClient = CSAccount.CreateCloudTableClient();
var CTable = CTClient.GetTableReference(tableName);
//確保沒有該張 Table 就建立
var resCreate = CTable.CreateIfNotExistsAsync().Result;
System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start();
Microsoft.WindowsAzure.Storage.Table.TableOperation operation = Microsoft.WindowsAzure.Storage.Table.TableOperation.Delete(
new User { RowKey = "USER333", PartitionKey = "GROUP4", ETag = "*" });
var res = CTable.ExecuteAsync(operation).Result;
Console.WriteLine("Success Delete");
stopwatch.Stop();
Console.WriteLine(stopwatch.Elapsed.ToString());
2. 更改資料 使用 ETag ,為何修改資料還要用 ETag ,其實你看Etag 格式他其實就是一個 timestamp 在某些修改動作下會驗證 ETag 原因就是因為確保你持有的是最新的資料進行修改,這方法很聰明,如果你撈回一筆資料,持有了一個月後再寫回去,中間已經不知道被更改過幾百次了,但是你無法根據最新的資料狀況作出判斷寫入, 至於哪些行為是需要 ETag 的,可以參考這個
https://docs.microsoft.com/zh-tw/azure/storage/common/storage-concurrency
之前那篇文章因為使用的是 InsertOrReplace 是不需要驗證 ETag 的,所以可以不用加上,但是如果有需要驗證 ETag 但是你也可以使用 * 進行強制覆寫 ,所以我在範例中是把一個物件讀出來改過之後再去修改,確保
ETag 是最新的,如果強制寫入,則把 ETag 改成 * 就可以了
code :
var connectionString = "your_connsction_string";
var tableName = "USERSAMPLE";
var CSAccount = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(connectionString);
var CTClient = CSAccount.CreateCloudTableClient();
var CTable = CTClient.GetTableReference(tableName);
//確保沒有該張 Table 就建立
var resCreate = CTable.CreateIfNotExistsAsync().Result;
System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start();
Microsoft.WindowsAzure.Storage.Table.TableOperation operation = Microsoft.WindowsAzure.Storage.Table.TableOperation.Retrieve("GROUP10", "USER999");
var user = CTable.ExecuteAsync(operation).Result.Result as User;
if (user != null)
{
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(user));
user.Name = "使用者" + 999 + "--更改過了第二次!!!";
var operationUpdate = Microsoft.WindowsAzure.Storage.Table.TableOperation.Replace(user);
var res = CTable.ExecuteAsync(operationUpdate).Result;
Console.WriteLine("Success");
}
else
{
Console.WriteLine("NODATA!");
}
stopwatch.Stop();
Console.WriteLine(stopwatch.Elapsed.ToString());
如果你覺得我寫得太簡單或是寫得不好,歡迎參考 :
https://docs.microsoft.com/zh-tw/dotnet/api/microsoft.windowsazure.storage.table?view=azure-dotnet
https://docs.microsoft.com/zh-tw/dotnet/api/microsoft.windowsazure.storage.table.tableentity?view=azure-dotnet
https://docs.microsoft.com/zh-tw/azure/storage/common/storage-concurrency