2016-02-23 40 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); 
    } 
} 
相關問題