加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – Azure october 2012 sdk – 如何删除表实体而不先检索它?

发布时间:2020-12-15 18:07:03 所属栏目:百科 来源:网络整理
导读:在以前的版本中,我们可以在不知道它是否存在的情况下删除实体. svc = new TestContext();item = new TestEntity("item2pk","item2rk");svc.AttachTo("TestTable",item,"*");svc.DeleteObject(item);svc.SaveChanges(); (source) 新的TableOperations没有此语
在以前的版本中,我们可以在不知道它是否存在的情况下删除实体.
svc = new TestContext();
item = new TestEntity("item2pk","item2rk");
svc.AttachTo("TestTable",item,"*");
svc.DeleteObject(item);
svc.SaveChanges();

(source)

新的TableOperations没有此语法.我必须使用这种旧方法还是有办法?我想保持一致,因为现在我的所有代码都使用了第2版的新类.

编辑:标题具有误导性

解决方法

您需要使用TableOperation.Delete:
var storageAccount = CloudStorageAccount.DevelopmentStorageAccount;
var table = storageAccount.CreateCloudTableClient()
                            .GetTableReference("tempTable");
table.CreateIfNotExists();

// Add item.
table.Execute(TableOperation.Insert(new TableEntity("MyItems","123")));

// Load items.
var items = table.ExecuteQuery(new TableQuery<TableEntity>());
foreach (var item in items)
{
    Console.WriteLine(item.PartitionKey + " - " + item.RowKey);
}

// Delete item (the ETAG is required here!).
table.Execute(TableOperation.Delete(new TableEntity("MyItems","123") { ETag = "*" }));

删除仅适用于存在的实体.即使旧客户端具有ContinueOnError选项,它也与批处理操作(as explained here)不兼容.

成功批量删除的唯一方法是,如果您不知道实体存在它,则首先添加它们(或者如果它们已经存在则替换它们):

var ensureItemsBatch = new TableBatchOperation();
ensureItemsBatch.InsertOrReplace(new MyEntity("MyItems","123") { Active = false });
ensureItemsBatch.InsertOrReplace(new MyEntity("MyItems","456") { Active = false });
ensureItemsBatch.InsertOrReplace(new MyEntity("MyItems","789") { Active = false });
table.ExecuteBatch(ensureItemsBatch);

var deleteItemsBatch = new TableBatchOperation();
deleteItemsBatch.Delete(new MyEntity("MyItems","123") { ETag = "*" });
deleteItemsBatch.Delete(new MyEntity("MyItems","456") { ETag = "*" });
deleteItemsBatch.Delete(new MyEntity("MyItems","789") { ETag = "*" });
table.ExecuteBatch(deleteItemsBatch);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读