SharePoint Choice Field, CAML and Enum

If you have already worked with LinQ to SharePoint you have definitely noticed that SPMetal generates enumerations to fit with Choice Field’s values. This feature is really interesting because it enables you to work with strongly-typed values instead strings. Of course this increases your code maintainability.

But LinQ to SharePoint has its pros and its many cons. So in some situations, CAML is the best to fit your needs like in the good old days.

That’s why I’ve written some lines of code to use enumerations with CAML.

ChoiceFieldValueAttribute

My solution is very close to the SPMetal behavior. I use a POCO to represent my data model. This object has an enumeration field which is mapped to a SharePoint Choice Field. On each value of the enumeration, I use a custom attribute to specify the associated SharePoint value.

Here is the code of the ChoiceFieldValueAttribute :

The Entity

Now let’s see how to use it in an entity which represents my data :

It’s realy easy to specify the mapping between the SharePoint values and the enumeration ones. Thanks to the static methods “ConvertToEnum” and “GetValue” you can easily convert SharePoint values to enumeration and vice-versa.

Getting the data

That’s fine but not enough. Here is an example of a business layer to retrieve the data from a SharePoint list and generates some entities :

GetActiveTasks

Here you can see that it is pretty easy to filter the elements of the SharePoint List thanks the enumeration and the ChoiceFieldValue attribute. The main purpose of this, is to easily maintain your code. If the choice field’s values change, you will just update the ChoiceFieldValue attributes at the enumeration level. Your conditions and queries will automatically be updated.

GetTasks

Thanks to the overloaded constructor I’m able to convert SharePoint items to Task entities. This also convert the values of the “Status” field to my strongly-typed enumeration.

AddTask

The AddTask method uses the CopyTo method of the Task entity to populates the SPListItem and converts the enumeration value to it’s SharePoint string representation.

Example

Download the attached solution to test the code in your SharePoint environment : WawawumEnumCAML.zip
Prerequisites :

  • Sign the project with your key.
  • Deploy the solution to a SharePoint site which contains a “Tasks” list with the default tasks template.
  • Ensure that the “Wawawum -Tasks list” feature is activated.
  • Add the “TasksList” WebPart to a page.