2016-01-20 58 views
0

有人能告訴我我在做什麼錯嗎?我試圖列表名稱傳遞給將刪除列表中的所有行的方法:按價值傳遞 - 列表名稱

public static void DeleteLastUpdate(Microsoft.SharePoint.Client.List oList) 
    { 
     using (var context = new ClientContext(FrontEndAppUrl)) 
     { 
      var ss = new System.Security.SecureString(); 
      Array.ForEach("hhh".ToCharArray(), (c) => { ss.AppendChar(c); }); 
      context.Credentials = new SharePointOnlineCredentials("yyy", ss); 
      var web = context.Web; 

      ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); 

      CamlQuery camlQuery = new CamlQuery(); 
      camlQuery.ViewXml = "<View><Query><OrderBy><FieldRef Name='ID' Ascending='TRUE' /></OrderBy></Query></View>"; 
      ListItemCollection collListItem = oList.GetItems(camlQuery); 
      context.Load(collListItem); 

      context.ExecuteQuery(); 



      foreach (ListItem oListItem in collListItem) 
      { 

       string i = oListItem["ID"].ToString(); ; 

       ListItem ListItemToDelete = oList.GetItemById(i); 

       ListItemToDelete.DeleteObject(); 

       context.ExecuteQuery(); 

      } 

      oList.Update(); 
     } 

    } 

    public static void GetCountry() 
    { 
     using (var context = new ClientContext(FrontEndAppUrl)) 
     { 
      Microsoft.SharePoint.Client.List oList_Country = context.Web.Lists.GetByTitle("LISTNAME"); 

      DeleteLastUpdate(oList_Country); 


     } 

    } 

我得到的錯誤是在context.Load(collListItem);

它說對象用在與對象關聯的上下文中。我怎麼可以將列表的值傳遞給Delete()方法?

回答

1

正是這個例外所說的是發生了什麼。您在GetCountry()的上下文中創建oList_Country,然後將其傳遞到DeleteLastUpdate(),您在其他環境中工作。

也許你應該考慮通過參數傳遞上下文到DeleteLastUpdate()。然後,您的代碼會變得這樣的事情:

public static void DeleteLastUpdate(ClientContext context, Microsoft.SharePoint.Client.List oList) 
{ 
    // You should not create a context here, but use the supplied context 
    // using (var context = new ClientContext(FrontEndAppUrl)) 
    // { 
     var ss = new System.Security.SecureString(); 
     ... 
} 

public static void GetCountry() 
{ 
    using (var context = new ClientContext(FrontEndAppUrl)) 
    { 
     Microsoft.SharePoint.Client.List oList_Country = context.Web.Lists.GetByTitle("LISTNAME"); 

     DeleteLastUpdate(context, oList_Country); // Pass the context 
+0

非常感謝您的回覆。你會友善地告訴我該怎麼做嗎? – SharePointDummy

+0

我用代碼示例更新了我的答案。 –

+0

Thansks!這工作完美 – SharePointDummy

1

我猜你可能會嘗試在GetCountry方法獲得的DeleteLastUpdate方法重用上下文。執行很多查詢時,BTW DeleteLastUpdate看起來效果不佳。