2010-01-14 43 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();