Deleting SharePoint field causing “Column *** does not exist” exception when loading ListItemAllFields
-
11-01-2021 - |
Question
I have a customized functionality to delete a SharePoint field in my SharePoint online site. I'm deleting the said field from content types, associated lists and finally deleting the site column itself through code.
But when I try to load a custom view of a content type, the below exception occurs.
Column '' does not exist. It may have been deleted by another user
I'm loading a document "File" and try to get "ListItemAllFields" to render some information on the view. The exception occurs on the below lines of code.
var templatedocument = ctx.Web.GetFileByServerRelativeUrl(contentType.DocumentTemplateUrl);
ctx.Load(templatedocument.ListItemAllFields);
ctx.ExecuteQuery();
I'm trying to figure out where the reference is coming from, as I have deleted the field from SharePoint.
Note: Surprisingly, the the issue does not occur after about 5 minutes.
The code to delete the field is as follows.
//// delete the field from Content type
foreach (var contentTypeName in contentTypeColection)
{
ContentType contentType = ctx.Web.GetContentTypeByName(contentTypeName);
FieldLink selectedField = contentType.FieldLinks.GetById(field.Id);
selectedField.DeleteObject();
contentType.Update(true);
ctx.Load(contentType);
ctx.ExecuteQuery();
//// Add Audit entry- delete field from content type
var audit = this.SaveAuditForDeleteFields(tenant, contentType.Id.ToString(), field.Title);
if (audit != null)
{
auditEntries.Add(audit);
}
}
//// delete the field from list content type
var listField = list.Fields.GetByInternalNameOrTitle(field.InternalName);
if (listField != null)
{
listField.DeleteObject();
ctx.ExecuteQuery();
}
//// delete the field from template library
var templateListField = templateList.Fields.GetByInternalNameOrTitle(field.InternalName);
if (templateListField != null)
{
templateListField.DeleteObject();
ctx.ExecuteQuery();
}
//// delete the field from site columns
field.DeleteObject();
ctx.ExecuteQuery();
Any idea on what's happening would be really helpful.
La solution
You've deleted the field but the list
object remains the same, meaning its representation in memory has not changed. So it's in a stale state.
Re-instantiate the list
object and you should be back in business. Optionally a list.Update()
might also do the trick.