2011-10-19 105 views
2

史蒂夫馬克思新UPSERT寫了關於新的擴展方法在Azure Table中存儲這裏的新存儲協議版本的一部分來執行upserts:避免在Azure Table中存儲

http://blog.smarx.com/posts/extension-methods-for-the-august-storage-features

但是,如果我想要什麼做無條件合併或投擲的原始操作,而不是頂點。我想合併一個對象,更新單個字段,但是如果實體不存在,則拋出,而不是創建一個僅包含我正在合併的屬性的新實體。

這可能嗎?請注意,我想在其他地方使用upsert,因此我已採取讓IoC爲我提供從GetDataServiceContext2011而不是GetDataServiceContext創建的上下文。我想我可以在兩者之間進行交替,但當Azure團隊更新官方庫時,這無濟於事。

根據MSDN

的插入或合併實體的操作使用MERGE動詞,並且必須是 使用2011-08-18版或更新版本調用。另外,它不使用If-Match頭部 。這些屬性將此操作與更新實體操作 區分開來,儘管兩個操作的請求主體都是相同的 。

所以,我怎麼存儲庫發出上省錢,而不是不發出If-Match在所有通配符If-Match

回答

5

只需使用AttachTo,並帶有一個用於etag的星號。這將導致If-Match: *。這裏有一個完整的工作示例:

class Entity : TableServiceEntity 
{ 
    public string Text { get; set; } 
    public Entity() { } 
    public Entity(string rowkey) : base(string.Empty, rowkey) { } 
} 
class Program 
{ 
    static void Update(CloudStorageAccount account) 
    { 
     var ctx = account.CreateCloudTableClient().GetDataServiceContext(); 

     var entity = new Entity("foo") { Text = "bar" }; 
     ctx.AttachTo("testtable", entity, "*"); 
     ctx.UpdateObject(entity); 
     ctx.SaveChangesWithRetries(); 
    } 

    static void Main(string[] args) 
    { 
     var account = CloudStorageAccount.Parse(args[0]); 
     var tables = account.CreateCloudTableClient(); 
     tables.CreateTableIfNotExist("testtable"); 
     var ctx = tables.GetDataServiceContext(); 

     try { Update(account); } catch (Exception e) { Console.WriteLine("Exception (as expected): " + e.Message); } 

     ctx.AddObject("testtable", new Entity("foo") { Text = "foo" }); 
     ctx.SaveChangesWithRetries(); 

     try { Update(account); } catch (Exception e) { Console.WriteLine("Unexpected exception: " + e.Message); } 

     Console.WriteLine("Now text is: " + tables.GetDataServiceContext().CreateQuery<Entity>("testtable").Where(e => e.PartitionKey == string.Empty && e.RowKey == "foo").Single().Text); 
     tables.DeleteTableIfExist("testtable"); 
    } 
} 
+0

謝謝。我對這件事感到很沮喪。 :-P –

+0

@smarx etag實際上做了什麼?我試圖谷歌,但沒有找到任何解釋。 – starcorn

+0

@starcom在這種情況下,問題本身給出了答案並提供了源代碼(MSDN)。 – smarx