Search code examples
c#sharepointcsom

The collection has not been initialized


I am trying to retrieve all items from a Sharepoint library with CSOM and create a list of it. I am sure it has something to do with the order of the code. The question is how?

ListItemCollection collListItem = oList.GetItems(camlQuery);
var newList = new List<Item>();
var items = oList.GetItems(camlQuery);
context.Load(collListItem);

context.ExecuteQuery();

foreach (var col in items)
{

    newList.Add(new Item()
    {
        ID = Convert.ToInt32(col["ID"]),

    });
}

I get the following error:

The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested


Solution

  • You should have loaded the items object not the collListItems thus your code should look following:

    ListItemCollection collListItem = oList.GetItems(camlQuery);
    var newList = new List<Item>();
    var items = oList.GetItems(camlQuery);
    context.Load(items);
    context.ExecuteQuery();