Archive

Archive for June, 2013

Using ContentTypeId in CAML Query

June 28, 2013 Leave a comment

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