Frage

I am attempting to create a lookup field on a list using CSOM. I have the Lookup vales defined in a ListTemplateType.GenericList named “User Status Types”. This setup appears fine and I can successfully create the field against this list in SharePoint itself.

The problem comes when I try to create the field on the target list (a column that references the lookup values in the generic list mentioned above).

I am submitting the following Xml via fieldCollection(xml, false, AddFieldOptions.AddToAllContentTypes)

<Field Type="Lookup" DisplayName="UserStatus" Description="System Activation Status" Required="TRUE" EnforceUniqueValues="FALSE" List="Lists/User Status Types" WebId="~sitecollection" Overwrite="TRUE" PrependId="TRUE" ShowField="Title" UnlimitedLengthInDocumentLibrary="FALSE" StaticName="Status" Name="Status" Hidden="FALSE" ReadOnly="FALSE" />

This list generates a ServerException “Value does not fall withing the expected range.”

Note that while referencing the list via the friendly name is ideal, I also have quick access to the Guid at any time. I’m also interested in the pitfalls of using a named reference as well.

War es hilfreich?

Lösung

The answer, in this case of using CSOM/c# client side, ends up being a combination of simplifying the XML and relying on post-add CSOM interactions.

In short, the above XML can be simplified to:

var lookupFieldXml = "<Field DisplayName="UserStatus" Type="Lookup" />";
var field = destinationList.Fields.AddFieldAsXml(lookupFieldXml, false, AddFieldOptions.AddToAllContentTypes);
lookupField = context.CastTo<FieldLookup>(field);
lookupField.LookupList = sourceLookupList.Id.ToString();
lookupField.LookupField = "Title";
// at this point, we can update against lookupField or field. It doesn't appear to matter.
field.Update();
context.ExecuteQuery();

A note about this solution - the key piece here is the explicit CastTo operator hanging off of the context. It is not a type-safe cast, you can cast any field to any other type of field and there are no complaints.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top