CAML Query to SharePoint list returns entire set

Jonathan picture Jonathan · Apr 3, 2014 · Viewed 25.4k times · Source

I've been running into an issue where if I execute a CAML query in C#, my ListItemCollection contains the entirety of the list. Here is a snippet of my scrubbed code maybe you can see what I've done wrong. While debugging, I've found that that the XML generated is what I expected with the values read from a file. There seems to be an issue with actually doing the query and loading the results. The steps I've done to do that here don't seem correct to me, I feel like I'm missing a step.

using Microsoft.SharePoint.Client;
...
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(user, password, domain);
ClientContext clientContext = new ClientContext(uri);
clientContext.Credentials = credentials;
List list = clientContext.Web.Lists.GetByTitle(listName);
//read line of input from file and save to string[]
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = "<Query><Where><And><Eq><FieldRef Name=\"Entity\" /><Value Type=\"Text\">" + columns[2].Trim() + "</Value></Eq><And><Eq><FieldRef Name=\"Title\"/><Value Type=\"Text\">" + columns[0].Trim() + "</Value></Eq><Eq><FieldRef Name=\"Section\" /><Value Type=\"Text\">" + columns[1].Trim() + "</Value></Eq></And></And></Where></Query>";
ListItemCollection listItems = list.GetItems(camlQuery);
clientContext.Load(listItems);
clientContext.ExecuteQuery();

Answer

Vadim Gremyachev picture Vadim Gremyachev · Apr 3, 2014

In SharePoint CSOM the root element for CamlQuery.ViewXml property is <View>, for example:

public CamlQuery CreateInventoryQuery(string searchSku)
{
   var qry = new CamlQuery();
   qry.ViewXml =
      @"<View>
         <Query>
          <Where>
            <BeginsWith>
              <FieldRef Name='SKU' />
              <Value Type='Text'>" + searchSku + @"</Value>
            </BeginsWith>
          </Where>
        </Query>
       </View>";
   return qry;
}

References

Using the Client Object Model