Coding Challenge: Unknown ContentTypeId in Document Library

I was recently working with a colleague on a SharePoint coding problem involving a ContentTypeId we had assumed was correct, but quickly found out was coming up as something completely unexpected.  We were performing a CAML query in C#, in which were were trying to retrieve the ContentType, and the unique ContentTypeId values.  The values we were expecting should have started 0x followed by 73 HEX characters (for example, 0x010100124D1872DA1E3C4AA5B8505A4E86197A00B05E965C40608049BB8C2C1218F7120D).  The query we formulated looked like below.

SPQuery sQuery = new SPQuery();

sQuery.Query = @"<Where><Eq><FieldRef Name=""ContentType"" /><Value Type=""Text"">My CT Value</Value></Eq></Where>";

sQuery.ViewFields = @"<FieldRef Name=""Title"" /><FieldRef Name=""ContentType"" />";

sQuery.IncludeMandatoryColumns = true;

The problem we were having was that all the results were coming back as the value 0x00C2208B8CE6E1422CADC1C521EAB2A68B instead (for distinctly different content types).  The other problem we eventually detected was that the ContentType had no value either.  So finally we brought out the big guns and went into the debugger.  As it turns out, this unknown ContentTypeId value (00C2208B8CE6E1422CADC1C521EAB2A68B) is the null content type value.

image

To resolve this problem, we found the following MSDN article, http://social.technet.microsoft.com/Forums/en-US/sharepoint2010programming/thread/5998657c-2c83-43d5-ab48-3197d2250778. In there, a comment from Ferovac described a proper method for solving this in the CAML query (note, there’s another proposed solution, but that solution requires you to re-write your query).  His suggestion was as follows, “I tried and managed to reproduce the same thing, but by adding also "<FieldRef Name="ContentTypeId" />" to ViewFields, I received the correct result.”. We simply changed the ViewFields line to the following, and it started returning the expected results.

sQuery.ViewFields = @"<FieldRef Name=""Title"" /><FieldRef Name=""ContentType"" /><FieldRef Name=""ContentTypeId"" />";

Important Note, we had assumed that because we had the statement “sQuery.IncludeMandatoryColumns = true;” in our code, that it would automatically include any fields (like ContentTypeId) which were necessary for a successful query.  This assumption was clearly negatory.