Recursive and Folder-Scoped LINQ Queries in SharePoint 2010
As you might experienced in SharePoint 2007, a CAML query is by default non recursive. In other words, if you execute a CAML query, you will end up with items from the list root folder. This is still the same in SharePoint 2010. You have to define extra query options as shown below in case you want to query all folders and sub folders within a list (Recursive Query) :
qry.ViewAttributes = "Scope='Recursive'";
And if you want to scope your query to a certain folder :
qry.Folder = list.ParentWeb.GetFolder("Folders DocLib/2008");
What about LINQ to SharePoint ?
The default behavior is the same, however if recursive querying is the desired behavior, you can use the ScopeToFolder method from your EntityList<T> object.
Note the following queries:
var q = dc.Projects.Where(p => p.DueDate < DateTime.Now.AddMonths(1));
var q = dc.Projects.ScopeToFolder("", true).Where(p => p.DueDate < DateTime.Now.AddMonths(1));
The first one executes against the list root folder while the second one is recursive. You might be wondering about the empty string that I’m passing to ScopeToFolder method. Well, let’s see what MSDN says about the parameters that the method expects.
public IQueryable<TEntity> ScopeToFolder( string folderUrl, bool recursive )
folderUrl –> The URL of the folder.
recursive –> true to include items in subfolders; false to exclude them.
That’s it, if you want to scope your LINQ query to a specific folder, pass the folder URL as the first parameter to the method & “true” if you want the recursive behavior of the query. In the second query, I just wanted the recursive behavior and I didn’t want to scope my query to any folders so I passed an empty string, this does the trick.
Hope this helps!
Comments
Anonymous
April 15, 2011
var dc = new SPLinq_QALibraryDocsDataContext(SPContext.Current.Web.Url); // var venkatPhotos = dc.Qldocs; var venkatPhotos = dc.Qldocs.ScopeToFolder("", true); var empQuery = from photo in venkatPhotos where photo.LinktoTemplate.Equals("Corporate") select new { photo.Title, photo.Path, photo.Name, }; when i execute this the folder url cannot be empty i guess it is throwing me errors abt the url of the folder what am i doing wrong here.Anonymous
May 25, 2014
SharePoint 2013 and ScopeToFolder - I've had Access Denied error caused by "System.InvalidOperationException: Cannot scope to folder as it does not exist". The problem is that ScopeToFolder("", true) uses root folder of the SPWeb and not root folder of the SPList! ScopeToFolder("Lists/SampleList") works fine. User with Access Denied problem is in site Visitors group with read permissions.