简体   繁体   中英

SharePoint CAML query works in builder but not in code

I have a query that is working when using any CAML query builder, when in using it in c# for a SharePoint web part, it always returns no results.

using (SPWeb ThisWeb = ThisSite.OpenWeb())
{
  IList<Tweet> Tweets = GetTweets(item["Mode"].ToString(), item["String"].ToString(), LastTweet, ThisSite);
  SPList ThisList = ThisWeb.Lists.TryGetList(Variables.TwitterTweetList);

  foreach (var tweet in Tweets)
  {
    SPListItemCollection itms = ThisList.GetItems(new SPQuery() { Query = @"<Where>" + 
        "<Eq>" +
        "<FieldRef Name=""Title"" />" +
        "<Value type=""Text"">" + tweet.tweetID.ToString() + "</Value>" +
        "</Eq>" +
        "</Where>"
  });

  if (itms.Count == 0)
  {
    // add the tweet to 'ThisList'
  }
}

}

Stepping into the code, you'll see tweet.tweetID.ToString() is "337958304577892353"

When running this code, it return ZERO items.

When running the query in U2U builder or any other CAML query it returns 1 (2, 3, 4, etc if the code is ran more then once).

Query ran in U2U builder:

<Query>
    <Where>
        <Eq>
            <FieldRef Name="Title" />
            <Value type="Text">"337958304577892353"</Value>
        </Eq>
    </Where>
</Query>

(Yes, when doing CAML in SharePoint, you drop the tags... I have 3 other queries that work just fine.. it's just this one.)

As a corollary to what Robbert said, have you tried declaring the tweet.tweetID.ToString() as its own variable? If nothing else, you can look at it in debug and confirm that it's passing the correct information to the SPList object.

foreach(var tweet in Tweets)
{
    string tweetID = tweet.tweetID.ToString();
    SPQuery query = new Query();
    query.Query = string.format(queryformat, tweetID);
    SPListItemCollection tweetItems = list.GetItems(query);
}

...and so on. My experience is that SharePoint will happily work with strings that happen to be a long row of digits. It's possible, however, that tweetID.ToString() isn't returning what you think it is, and as such a cast ( (string)tweetID or ((long)tweetID).ToString() ) is necessary instead.

Well may be you sorted out this issue but may thats because of a simple reason that you are using double quotation within double quotation. like in the following CAML query.

    "<Eq>" +
    "<FieldRef Name='Title' />" +
    "<Value type='Text'>" + tweet.tweetID.ToString() + "</Value>" +
    "</Eq>" +
    "</Where>"

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