简体   繁体   中英

CAML Query to SharePoint list returns entire set

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();

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

So after a long search I've determined it was an issue with the CAML Query itself. Apparently I need to enclose the XML with a VIEW tag or else it doesn't even execute the query. The following change actually works for some reason.

camlQuery.ViewXml = "<View><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></View>";

Solution source

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM