Home > SharePoint, SharePoint 2010, SharePoint 2013, Uncategorized > Using ContentTypeId in CAML Query

Using ContentTypeId in CAML Query


You can specify a Content Type Id in a CAML Query using the <FieldRef Name=’ContentTypeId’ /> clause. But to make this query works, you have to specify the right Value Type. Using “Text” or “Computed” mays works on some environments but fails on others…

It seems that the best choice is to use the “ContentTypeId” value type. This value type works pretty well with the Equals, or BeginsWith Condition.

Example:

           using (SPSite site = new SPSite(SiteURL))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists[ListName];
                    SPQuery qry = new SPQuery();
                    qry.Query=String.Format(@"
                       <Where>
                            <And>
                                <Eq>
                                    <FieldRef Name='Title'/>
                                    <Value Type='Text'>{0}</Value>
                                </Eq>
                                <BeginsWith>
                                    <FieldRef Name='ContentTypeId'/>
                                    <Value Type='ContentTypeId'>{1}</Value>
                                </BeginsWith>
                            </And>  
                        </Where>",myDocumentTitle,myContentTypeID);
                    var myItem=list.GetItems(qry);

This article mention main value types, but the ContentTypeId is missing there.

Thanks Pierre

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: