2016-02-23 12 views
0

我现在可以通过调用item.DeleteChildren()来删除项目,如果有错误,我想通过原始项目列表var originalItems = item.GetChildren();来恢复这些项目,但是如何恢复这些项目以便这些模板字段中的值也保留?如何以编程方式恢复子Sitecore项目?

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

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

回答

3

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

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

代码通过约翰·西

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(); 
    } 
} 

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

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); 
    } 
} 
相关问题