SPSiteDataQuery Returns Only One List Type At A Time
- by Brian Jackett
The SPSiteDataQuery class in SharePoint 2007 is very powerful, but it has a few limitations. One of these limitations that I ran into this morning (and caused hours of frustration) is that you can only return results from one list type at a time. For example, if you are trying to query items from an out of the box custom list (list type = 100) and document library (list type = 101) you will only get items from the custom list (SPSiteDataQuery defaults to list type = 100.) In my situation I was attempting to query multiple lists (created from custom list templates 10001 and 10002) each with their own content types. Solution Since I am only able to return results from one list type at a time, I was forced to run my query twice with each time setting the ServerTemplate (translates to ListTemplateId if you are defining custom list templates) before executing the query. Below is a snippet of the code to accomplish this. SPSiteDataQuery spDataQuery = new SPSiteDataQuery();
spDataQuery.Lists = "<Lists ServerTemplate='10001' />";
// ... set rest of properties for spDataQuery
var results = SPContext.Current.Web.GetSiteData(spDataQuery).AsEnumerable();
// only change to SPSiteDataQuery is Lists property for ServerTemplate attribute
spDataQuery.Lists = "<Lists ServerTemplate='10002' />";
// re-execute query and concatenate results to existing entity
results = results.Concat(SPContext.Current.Web.GetSiteData(spDataQuery).AsEnumerable());
Conclusion
Overall this isn’t an elegant solution, but it’s a workaround for a limitation with the SPSiteDataQuery. I am now able to return data from multiple lists spread across various list templates. I’d like to thank those who commented on this MSDN page that finally pointed out the limitation to me. Also a thanks out to Mark Rackley for “name dropping” me in his latest article (which I humbly insist I don’t belong in such company) as well as encouraging me to write up a quick post on this issue above despite my busy schedule. Hopefully this post saves some of you from the frustrations I experienced this morning using the SPSiteDataQuery. Until next time, Happy SharePoint’ing all.
-Frog Out
Links
MSDN Article for SPSiteDataQuery
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spsitedataquery.lists.aspx