2

作为新存储协议版本的一部分,Steve Marx 在此处撰写了有关在 Azure 表存储中执行 upsert 的新扩展方法:

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

但是,如果我想做无条件合并或抛出的原始操作,而不是 upsert 怎么办。我想合并一个对象,更新单个字段,但如果实体不存在则抛出,而不是创建一个仅包含我正在合并的属性的新实体。

这可能吗?请注意,我想在其他地方使用 upsert,所以我已经开始让 IoC 为我提供从而GetDataServiceContext2011不是GetDataServiceContext. 我想我可以在两者之间交替,但是当 Azure 团队更新官方库时,这将无济于事。

根据MSDN

插入或合并实体操作使用 MERGE 动词,并且必须使用 2011-08-18 版本或更高版本调用。此外,它不使用 If-Match 标头。这些属性将此操作与更新实体操作区分开来,尽管这两个操作的请求正文是相同的。

那么,如何让存储库If-Match在保存时发出通配符而不是根本不发出If-Match

4

1 回答 1

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");
    }
}
于 2011-10-19T16:35:42.120 回答