Removing a Site Column from a Content Type using the Client Object Model

I don’t know how many hours I have spent trying to remove a site column using CSOM. There is a specifc way to do so and you have to do it in the right order. Below is how you would remove a site column that has been provisioned to a SharePoint site, is associated with a Content Type, and is also added to a list.

First you need to get a reference of the field:

ClientContext cc = new ClientContext(siteUrl);
cc.AuthenticationMode = ClientAuthenticationMode.Default;
cc.Credentials = new SharePointOnlineCredentials(userName, pwd);
Web web = cc.Web;

Field field = web.Fields.GetByInternalNameOrTitle(fieldName);
cc.Load(field);
cc.ExecuteQuery();

Next, you need to use the FieldLink object to remove the site column from the content type:

ContentType cType = web.GetContentTypeByName(cTypeName);
FieldLink cTypeField = cType.FieldLinks.GetById(field.Id);
cTypeField.DeleteObject();
cType.Update(true);
cc.Load(cType);
cc.ExecuteQuery();

It is critical to call an Update() on the content type before executing your query.

The next step is to remove the site column from your list as it will be orphaned if you don’t.

List list = web.Lists.GetByTitle(listName);
cc.Load(list);
cc.ExecuteQuery();

if (list.FieldExistsByName(fieldName))
{
     list.Fields.GetByInternalNameOrTitle(fieldName).DeleteObject();
     cc.ExecuteQuery();
}

Finally, remove the site column itself:

field.DeleteObject();
cc.ExecuteQuery();

 

Advertisements