集合尚未初始化

The collection has not been initialized

我正在尝试使用 CSOM 从 Sharepoint 库中检索所有项目并创建它的列表。我确信它与代码的顺序有关。问题是如何?

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"]),

    });
}

我收到以下错误:

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

您应该加载 items 对象而不是 collListItems 因此您的代码应该如下所示:

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