3

I am using the below code

    Web rootWeb = clientContext.Site.RootWeb;    
    rootWeb.Fields.AddFieldAsXml("<Field DisplayName='Session Name' Name='SessionName' ID='"+new GUID()+"' Group='SharePoint Saturday 2014 Columns' Type='Text' />", false, AddFieldOptions.AddFieldInternalNameHint);
    clientContext.ExecuteQuery();
    Field session = rootWeb.Fields.GetByInternalNameOrTitle("SessionName");
    ContentType sessionContentType = rootWeb.ContentTypes.GetById("0x0100BDD5E43587AF469CA722FD068065DF5D");
    sessionContentType.FieldLinks.Add(new FieldLinkCreationInformation 
    {
        Field = session
    });
    sessionContentType.Update(true);
    clientContext.ExecuteQuery();

This creates a site column and adds it to the group, but when I try to attach it to a content type it throws

duplicate "SessionName" found

I also get the below error sometimes

The field specified with name "SessionName" and ID{some-id} is not accessible or does not exist

After creating site column using this code, I am not able to add site column to content type manually!!

It throws the same error

3

I have faced this issue before. The error says that there already exists a column named SessionName. Replace SessionName with SessionNameTest and try. Mostly this will solve your issue.

  • Thanks Mancy, I tried changing the names too but no luck – Vignesh Subramanian Sep 29 '15 at 11:22
3

I removed the ID parameter in the column creation and it worked fine

  Web rootWeb = clientContext.Site.RootWeb;    
    rootWeb.Fields.AddFieldAsXml("<Field DisplayName='Session Name' Name='SessionName'  Group='SharePoint Saturday 2014 Columns' Type='Text' />", false, AddFieldOptions.AddFieldInternalNameHint);
    clientContext.ExecuteQuery();
    Field session = rootWeb.Fields.GetByInternalNameOrTitle("SessionName");
    ContentType sessionContentType = rootWeb.ContentTypes.GetById("0x0100BDD5E43587AF469CA722FD068065DF5D");
    sessionContentType.FieldLinks.Add(new FieldLinkCreationInformation 
    {
        Field = session
    });
    sessionContentType.Update(true);
    clientContext.ExecuteQuery();
1

But to be useful i guess you need to set name through a variable like

string columnName;
string groupName;

rootWeb.Fields.AddFieldAsXml("<Field DisplayName='"+columnName+"' Name='" + columnName + "' Group='" + groupName + "' Type='Text' />", false, AddFieldOptions.AddFieldInternalNameHint);

Then you can add it to a list

string listName;

List addColumnList = web.Lists.GetByTitle(listName);
Field newColumn = web.Fields.GetByInternalNameOrTitle(columnName);
addColumnList.Fields.Add(newColumn);
context.ExecuteQuery();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.