Citizen SP
Citizen SP

Reputation: 1411

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

Upvotes: 4

Views: 25272

Answers (2)

Hiếu Vũ
Hiếu Vũ

Reputation: 1

I have a same problem, then I recalled ExecuteQuery() below foreach loop and that worked for me

 ListItemCollection recruitmentItems= Recuitment.GetItems(camlQuery);
                cc.Load(recruitmentItems, items => items.Include(
                       x => x.Id,
                       x => x["Title"],
                       x => x["Email"],
                       x => x["Phone"]
                ));
                cc.ExecuteQuery();
                foreach (ListItem item in recruitmentItems)
                {
                    ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                    ListItem newItem = Applicant.AddItem(itemCreateInfo);
                    newItem["Title"] = item["Title"];
                    newItem["Email"] = item["Email"];
                    newItem["PhoneNumber"] = item["Phone"];
                    newItem.Update();
                }
                cc.ExecuteQuery();

Upvotes: 0

nizzik
nizzik

Reputation: 826

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();

Upvotes: 9

Related Questions