Recently, I had a situation where I need to add site columns (available in root web) to a content type reference in a particular list under a particular web.
I wrote the code below
var field = web.Site.RootWeb.AvailableFields[new Guid("<<FieldID>>")]; foreach (SPContentType cType in web.Lists["ListName"].ContentTypes) { cType.Fields.Add(field); cType.Update(); }
but it was not working as expected and throwing the below exception
"This functionality is unavailable for field collections not associated with a list."
After some research, I came to know that the field needs to be added as a SPFieldLink and not as SPField itself since the field already exists in the root web. The below modified code is working fine for me.
var field = web.Site.RootWeb.AvailableFields[new Guid("<<FieldID>>")]; foreach (SPContentType cType in web.Lists["ListName"].ContentTypes) { SPFieldLink fieldLink = new SPFieldLink(field); cType.FieldLinks.Add(fieldLink); cType.Update();
}
Hopefully this helps some one or may be myself in the future when I struggle with the same issue.
Thanks
Senthil S