2010-01-14 44 views
1

使用下面的代碼塊中,listItem.Update失敗,一個NullReferenceException:SPListItem.Update失敗

 SPWeb web = null; 
     SPList list = null; 
     SPListItem listItem = null; 
     try 
     { 
      SPSecurity.RunWithElevatedPrivileges(delegate() 
      { 
       using (SPSite site = new SPSite(this.SiteUrl)) 
       { 
        web = site.OpenWeb(); 
        list = web.Lists[this.ListName]; 
        listItem = list.Items.Add(); 
        listItem["Background"] = "foo"; 

       } 
      } 
      ); 
      listItem.Update(); 
     } 
     catch 
     { 
     } 
     finally 
     { 
      web.Dispose(); 
     } 

如果我移動listItem.Update()方法匿名委託的內部,我得到「操作由於對象的當前狀態而無效「。

是的,我梳理了SO,並嘗試了很多排列沒有成功。

任何想法?

更新: 第一評論後,我試圖從代碼中刪除匿名委託,看它是否表現更好:

// store the selected item to pass between methods 
    public T SelectedItem { get; set; } 

    // set the selected item and call the delegate method 
    public virtual void Save(T item) 
    { 
     SelectedItem = item; 
     try 
     { 
      SPSecurity.RunWithElevatedPrivileges(SaveSelectedItem); 
     } 
     catch 
     { 
     } 
    } 

    public virtual void SaveSelectedItem() 
    { 
     if (SelectedItem != null) 
     { 

      using (SPSite site = new SPSite(this.SiteUrl)) 
      { 
       using(SPWeb web = site.OpenWeb()) 
       {      
        SPList list = web.Lists[this.ListName]; 
        SPListItem listItem = list.Items.Add(); 
        //UpdateListItem(listItem, SelectedItem); 
        listItem["Background"] = "foo"; 
        listItem.Update(); 
       } 
      }  
     } 
    } 

而且這仍然不能解決「操作無效由於目前物體的狀態「。在這兩個代碼示例中,它看起來都像site.Impersonating是false。我在web.config中使用Windows身份驗證和模擬。這是從ASP.Net開發服務器運行的。

回答

1

我從這個網站(blackninjasoftware)找到了一個例子。我創建對該站點的引用,獲取其SystemAccount標記,然後使用管理標記創建對該站點的另一個引用。起初我對它似乎有些ha - - 但嘿 - 我有一個最後期限。

最終工作方法的身體現在的樣子:

  SPListItem new_item = null; 
      SPSite initialSite = new SPSite(this.SiteUrl); 
      using (var site = new SPSite(this.SiteUrl, initialSite.SystemAccount.UserToken)) 
      { 
       // This code runs under the security context of the SHAREPOINT\system 
       // for all objects accessed through the "site" reference. Note that it's a 
       // different reference than SPContext.Current.Site. 
       using (var elevatedWeb = site.OpenWeb()) 
       { 
        elevatedWeb.AllowUnsafeUpdates = true; 
        SPList list = elevatedWeb.Lists[this.ListName]; 
        new_item = list.Items.Add(); 
        UpdateListItem(new_item, item); 
        if (new_item != null) 
        { 
         new_item.Update(); 
        } 
       } 
      } 
      initialSite.Dispose();