Hi, folks today we are discussing the most common issue while retrieving a collection object using CSOM (Client-side object model) in SharePoint 2013/2016/Online. Here we will see how to resolve the error: ‘Microsoft.SharePoint.Client.CollectionNotIntitializedException’ occurred. 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.
Recently while working with .Net managed client object model (csom) in a Provider hosted add-in for SharePoint Online, I got the below error.
‘Microsoft.SharePoint.Client.CollectionNotIntitializedException’ occurred in SiteCreation.exe.
Additional information: 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.
The full error looks like below:
The collection has not been initialized. It has not been requested or the request has not been executed.
To resolve this whenever we are using any collection object inside loop we need to make sure initialization should happen outside the loop and before using it should be loaded and executed as shown below with an example.
In below we are trying to retrieve entire content types collection of a root site level and want to perform some action. So here is the proper way of initializing and usages.
ContentTypeCollection contentTypeColl = clientContext.Site.RootWeb.ContentTypes;
clientContext.Load(contentTypeColl);
clientContext.ExecuteQuery();
List list = clientContext.Web.Lists.GetByTitle(listURL);
clientContext.Load(list);
clientContext.ExecuteQuery();
#region Adding content types to List
string[] contentTypesStack = contentTypeName.Split(‘|’);
for (int i = 0; i < contentTypesStack.Length; i++)
{
if (contentTypesStack[i] != Constant.NOT_APPLICABLE)
{
ContentTypeId contentTypeGuid = GetContentTypeIdByName(clientContext, contentTypesStack[i], contentTypeColl);
}
}
You may like the following SharePoint CSOM tutorials:
- Copy list items from one list to another in SharePoint programmatically using CSOM
- Steps to add items from CSV file to SharePoint Online List using PowerShell in CSOM
- How to Use CAML Query for Boolean field for SharePoint 2013/2016/Online Object Model CSOM
- Create an index in SharePoint Online list using CSOM
- Activate SharePoint Server Publishing Feature programmatically using CSOM
- SharePoint rest api create a folder
- SharePoint Online console application with csom
Hope this will be helpful to resolve The collection has not been initialized. It has not been requested or the request has not been executed error in SharePoint Online or SharePoint 2016/2013.
Bhawana Rathore is a Microsoft MVP (3 times in Office Apps & Services) and a passionate SharePoint Consultant, having around 10 years of IT experience in the industry, as well as in .Net technologies. She likes to share her technical expertise in EnjoySharePoint.com and SPGuides.com