简体   繁体   English

CamlQuery - 如何在C#中使用Where子句

[英]CamlQuery - How to use Where clause in C#

I'm very new to CamlQuery and need a bit of help getting this to work. 我是CamlQuery的新手,需要一些帮助才能让它工作。

I installed a tool called CamlDesigner to help me generate the XML needed to filter a collection in Sharepoint, but the XML query that CamlDesigner constructs does not work in my C# codebehind. 我安装了一个名为CamlDesigner的工具来帮助我生成在Sharepoint中过滤集合所需的XML,但是CamlDesigner构造的XML查询在我的C#代码隐藏中不起作用。 I have an ID field that I am trying to filter by and I simply want to retrieve an item from Sharepoint where ID = 1 (or 2 or 3 or whatever). 我有一个ID字段,我试图过滤,我只想从Sharepoint检索ID = 1(或2或3或其他)的项目。

Here is the Caml query generated by the designer: 以下是设计人员生成的Caml查询:

   <Where>
      <Eq>
         <FieldRef Name='ID' />
         <Value Type='Counter'>1</Value>
      </Eq>
   </Where>

Here is my C# code where I am attempting to incorporate this Caml query. 这是我的C#代码,我试图合并这个Caml查询。 The C# works, but it is returning every item from "My SP Coll" as opposed to only returning the item where ID equals 1 . C#工作, 但它返回“My SP Coll”中的每个项目,而不是仅返回ID等于1的项目

// Sharepoint web service to retrieve categories items there
ClientContext clientContext = new ClientContext("https://myweb.dev.com/SP");
List oList = clientContext.Web.Lists.GetByTitle("My SP Coll");

CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = "<Query><Where><Eq><FieldRef Name='ID'/><Value type='Counter'>" + ID.ToString() + "</Value></Eq></Where></Query>";
Microsoft.SharePoint.Client.ListItemCollection collListItem = oList.GetItems(camlQuery);

clientContext.Load(collListItem);
clientContext.ExecuteQuery();

foreach (Microsoft.SharePoint.Client.ListItem oListItem in collListItem) {
     string ID = oListItem["ID"].ToString();
}

Thanks for the help! 谢谢您的帮助!

  1. The query needs to be wrapped in a <View>...</View> element, in addition to the <Query> element. 除了<Query>元素之外,查询还需要包装在<View>...</View>元素中。

  2. As per the generated query, the field name is ID not Id . 根据生成的查询,字段名称为ID而不是Id

On a side note, make sure you're disposing of the client context. 另外,请确保您处理客户端上下文。

And of course, to get an item by ID you can bypass this entire process and just use 当然,要按ID获取项目,您可以绕过整个过程并使用

var item = list.GetItemById(ID);

The ViewXml property just points to a view within a list and doesn't appear to handle filtering. ViewXml属性只指向列表中的视图,但似乎不处理过滤。

If you were to set up an already-filtered view and point the ViewXml to that, then you would still grab all items in the view, but since the view itself is filtered, your result set would match it. 如果您要设置已经过滤的视图并将ViewXml指向该视图,那么您仍然会获取视图中的所有项目,但由于视图本身已被过滤,因此您的结果集将与之匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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