Поделиться через


SharePoint View CAML [Me] query not returning items belonging to me even though I'm logged on as... Me.

The short answer... When creating a view through code that targets a field of type "User", the following CAML will not work

<Where><Eq><FieldRef Name="MyUserField" /><Value Type="User">[Me]</Value></Eq></Where>
nor this
<Where><Eq><FieldRef Name="MyUserField" LookupId="True" /><Value Type="User">[Me]</Value></Eq></Where>
nor this
<Where><Eq><FieldRef Name="MyUserField" LookupId="True" /><Value Type="Lookup">[Me]</Value></Eq></Where>

this works

<Where><Eq><FieldRef Name="MyUserField" /><Value Type="Integer"><UserID Type="Integer" /></Value></Eq></Where>

The long answer...

I recently created a view through C# CSOM to return records where the logged on user was equal to the value of a “User” field. Oddly, no records were returned when I looked at the view, even though my user account was the value of this field in several list items. Even more puzzling, when I edited the view through the SharePoint UI, it looked correct. Even more puzzling still, if I clicked the OK button to save the view it started working and all of the records where the “User” field was equal to “Me” were displayed.

 

So I used SharePoint Manager to do a comparison of what my query looked like before and after I clicked the OK button through the UI and noticed that my query had been changed from

<Where><Eq><FieldRef Name="MyUserField" /><Value Type="User">[Me]</Value></Eq></Where>

To

<Where><Eq><FieldRef Name=" MyUserField " /><Value Type="Integer"><UserID Type="Integer" /></Value></Eq></Where>

SharePoint Manager is an awesome tool for plumbing the depths and getting down to the nitty gritty of all of the objects in your farm, if you've not tried it, you should.

 
The final code comes out looking something like this

ClientContext cc = new ClientContext(https://my.SharePoint.url);
List l = cc.Web.GetListByTitle("My List");
string[] viewFieldsArray = null;
Systen.Collections.Generic.List <String> viewFields = new List<string>();
viewFields.Add("LinkTitle");
viewFields.Add("Field 1");
viewFields.Add("Field 2");
viewFieldsArray = viewFields.ToArray();
string filter = string.Format("<Where><Eq><FieldRef Name=\"MyUserField\" /><Value Type=\"Integer\"><UserID Type=\"Integer\" /></Value></Eq></Where>");
l.Views.Add(new ViewCreationInformation() { Title = "My Records", ViewFields = viewFieldsArray, Query = filter, RowLimit = 30, Paged = true, SetAsDefaultView = false });
cc.ExecuteQuery();

Comments

  • Anonymous
    November 24, 2014
    Nice, thanks!