如何以编程方式恢复子 Sitecore 项目?

How to programmatically restore children Sitecore items?

我目前可以通过调用 item.DeleteChildren() 删除项目,如果出现错误,我想通过使用原始项目列表 var originalItems = item.GetChildren(); 来恢复这些项目,但是我该如何恢复它们,以便这些模板字段中的值还保留吗?

我尝试执行以下操作,但所做的只是重新创建没有字段值的模板。

foreach (Item backupItem in backupItems)
{
    item.Add(backupItem.Name, backupItem.Template);
}

您可以将它们存档而不是删除它们,并在需要时恢复它们。

http://www.sitecore.net/learn/blogs/technical-blogs/john-west-sitecore-blog/posts/2013/08/archiving-recycling-restoring-and-deleting-items-and-versions-in-the-sitecore-aspnet-cms.aspx

来自 John West 的代码

Sitecore.Data.Items.Item item = Sitecore.Context.Item;
Sitecore.Diagnostics.Assert.IsNotNull(item, "item");
Sitecore.Data.Archiving.Archive archive = 
Sitecore.Data.Archiving.ArchiveManager.GetArchive("archive", item.Database);

foreach (Sitecore.Data.Items.Item child in item.Children)
{
  if (archive != null)
  {
    // archive the item
    archive.ArchiveItem(child);
    // to archive an individual version instead: archive.ArchiveVersion(child);
  }
  else
  {
    // recycle the item
    // no need to check settings and existence of archive
    item.Recycle();
    // to bypass the recycle bin: item.Delete();
    // to recycle an individual version: item.RecycleVersion();
    // to bypass the recycle bin for a version: item.Versions.RemoveVersion();
  }
}

要恢复,请使用相同的存档 class。

using (new SecurityDisabler())
{
    DateTime archiveDate = new DateTime(2015, 9, 8);
    string pathPrefix = "/sitecore/media library";

    // get the recyclebin for the master database
    Sitecore.Data.Archiving.Archive archive = Sitecore.Data.Database.GetDatabase("master").Archives["recyclebin"];

    // get as many deleted items as possible 
    // where the archived date is after a given date 
    // and the item path starts with a given path
    var itemsRemovedAfterSomeDate =
        archive.GetEntries(0, int.MaxValue)
                .Where(entry => 
                    entry.ArchiveDate > archiveDate && 
                    entry.OriginalLocation.StartsWith(pathPrefix)
                ).ToList();

    foreach (var itemRemoved in itemsRemovedAfterSomeDate)
    {
        // restore the item
        archive.RestoreItem(itemRemoved.ArchivalId);
    }
}