如何使用ETag对Azure表存储实体进行条件更新

时间:2014-04-03 09:09:05

标签: azure azure-table-storage

如果ETag未更改,如何使用Azure表存储实体的ETag更新实体?

示例:

   var query = (from ent in cloudservicetable.CreateQuery<CloudServiceTableEntity>()
               where ent.PartitionKey == "test"
               && ent.Status == "creating"
               && ent.Counter> 0
               select ent).AsTableQuery();



    var candidates = query.OrderByDescending(s=>s.Counter).ToList();
    bool found = false;
    while (!found && candidates.Any())
    {
        //Find best candidate
        var candidate = candidates.First();

        //If we can decrement the count with out the entity have been changed
        //it is a acceptable candidate.
        candidate.Counter--;
        var opr = TableOperation.Merge(candidate);
       // cloudservicetable.ExecuteAsync(opr) 
       // How do I only do the merge if the etag have not changed?

       //TODO If changed remove/update the candidate list

    }
    // if found we have a candidate

1 个答案:

答案 0 :(得分:4)

对于条件合并,您不必执行任何操作。如果在合并操作PreCondition期间不匹配,您的代码将抛出错误(Http Status Code 412失败 - ETag)。因此,上面的代码将完美无缺。

对于无条件合并,您需要手动将实体的ETag属性设置为*