Problems with the SPSiteDataQuery and Content Type Name

1 minute read

Last week a colleague and I  were working on a solution to find items by its content type within a site collection using the SPSiteDataQuery.

When we moved the solution to the testing environment we discovered that the solution was only returning results that were in a single list.

the code we used was the following:

SPSiteDataQuery query = new SPSiteDataQuery();
query.Webs = "<Webs Scope=\"Recursive\">";
 
//Ask for all lists created from the contacts template.
query.Lists = "<Lists BaseType='1' MaxListsLimit='0'/>";
 
// Get the Title (Last Name) and FirstName fields.
query.ViewFields = "<FieldRef Name=\"Dossiername\" />";
query.ViewFields += @"<FieldRef Name='Dossiernumber'/>";
query.ViewFields += @"<FieldRef Name='ContentType'/>";
 
string where = "<Where><Eq>";
where += "<FieldRef ID='ContentType' />";
where += "<Value Type='Computed'>Dossier</Value>";
where += "</Eq></Where>";
 
query.Query = where; 
  
DataTable results = web.GetSiteData(query);
 
foreach (DataRow row in results.Rows){
    Console.WriteLine("{0} -- {1} -- {2}", row["ContentType"], row["Dossiername"], row["Dossiernumber"]);
}

So this code only returns the items from 1 list. You can solve this problem by searching on the content type id, instead of the content type name. Like the code below:

SPSiteDataQuery query = new SPSiteDataQuery();
query.Webs = "<Webs Scope=\"Recursive\">";
 
query.Lists = "<Lists BaseType='1' MaxListsLimit='0'/>";
 
query.ViewFields = "<FieldRef Name=\"Dossiername\" />";
query.ViewFields += @"<FieldRef Name='Dossiernumber'/>";
query.ViewFields += @"<FieldRef Name='ContentType'/>";
 
SPContentType cTypeCollection = web.ContentTypes["Dossier"];
string where = string.Format(
                  @"<Where>
                    <BeginsWith>
                        <FieldRef Name='ContentTypeId'/>
                             <Value Type='Text'>{0}</Value>
                     </BeginsWith>
                  </Where>", cTypeCollection.Id);

// Set the query string.
query.Query = where; 
 
 
DataTable results = web.GetSiteData(query);
 
foreach (DataRow row in results.Rows){
    Console.WriteLine("{0} -- {1} -- {2}", row["ContentType"], row["Dossiername"], row["Dossiernumber"]);
}