The property or field Id has not be initialized. It has not been requested or the request has not been executed error in SharePoint

This SharePoint csom tutorial, we will discuss how to solve error The property or field ‘Url’ has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested which comes while working with SharePoint Online Office 365.

Recently I was working with SharePoint csom (.net managed object model) code for SharePoint Online sites. There is a requirement was to retrieve web Id. So we have developed a console application which was communicating to SharePoint Online sites.

In the code, I was writing below to retrieve the web site details like ServerRelativeUrl and RootWeb details.

using (ClientContext context = new ClientContext("https://onlysharepoint2013.sharepoint.com/sites/Bhawana/"))
{
context.AuthenticationMode = ClientAuthenticationMode.Default;
context.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(),GetSPOSecureStringPassword());
context.Load(context.Web, w => w.ServerRelativeUrl);
context.Load(context.Site.RootWeb, w => w.Id, w => w.Url);
context.Load(context.Web, w => w.Id);
string rootWebURL = context.Site.RootWeb.Url;
}

When I execute the above code the below exception comes in the below line:

string rootWebURL = context.Site.RootWeb.Url;

The error says:
An unhandled exception of type ‘Microsoft.SharePoint.Client.PropertyOrFieldNotInitializedException’ occurred in Microsoft.SharePoint.Client.Runtime.dll

Additional information: The property or field ‘Url’ has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.

It looks like below:

The property or field ‘Url’ has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.

The mistake I was doing was not to call the ExecuteQuery() method after loading the properties.

context.ExecuteQuery();

Below is the full code:

using (ClientContext context = new ClientContext("https://onlysharepoint2013.sharepoint.com/sites/Bhawana/"))
{
context.AuthenticationMode = ClientAuthenticationMode.Default;
context.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(),GetSPOSecureStringPassword());
context.Load(context.Web, w => w.ServerRelativeUrl);
context.Load(context.Site.RootWeb, w => w.Id, w => w.Url);
context.Load(context.Web, w => w.Id);
context.ExecuteQuery();
string rootWebURL = context.Site.RootWeb.Url;
}

You may like following SharePoint CSOM tutorials:

Hope this will be helpful to solve SharePoint error The property or field ‘Url’ has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.

Donwload Hub site pdf

Download SharePoint Online Tutorial PDF FREE!

Get update on Webinars, video tutorials, training courses etc.

>