Tuesday, July 30, 2013

Linq 2 Sharepoint works across site collections in Sharepoint 2013

Do you remember that one of the limitation of Linq 2 Sharepoint 2010 was that it didn’t support cross site collections. Developers found workaround for this limitation, see e.g. here: Using LINQ to SharePoint between site collections. But the fact was that Linq 2 Sharepoint didn’t support cross site collections queries OTB. Microsoft.SharePoint.Linq.DataContext class had only one constructor which receives url of the target web site.

   1:  public DataContext(string requestUrl)
   2:  {
   3:      ...
   4:  }

The good news is that in Sharepoint 2013 new overridden constructor was added to the DataContext class with 2nd boolean parameter crossSiteCollection. So if you need context working with different site collection you need to pass true in this parameter:

   1:  public DataContext(string requestUrl, bool crossSiteCollection)
   2:  {
   3:      ...
   4:  }

I didn’t find any additional parameters in SPMetal parameters schema, so SPMetal still generates strongly typed classes for current site collection only. But it is quite easy to fix: open file with generated data context and find where inheritor of DataContext class calls base constructor:

   1:  public partial class MyDataContext : Microsoft.SharePoint.Linq.DataContext {
   2:      public MyDataContext(string requestUrl) : 
   3:          base(requestUrl) {
   4:          ...
   5:      }
   6:      ...
   7:  }

In the example above this is the line 3. You need to add true to the base constructor call manually, so the final code will look like this:

   1:  public partial class MyDataContext : Microsoft.SharePoint.Linq.DataContext {
   2:      public MyDataContext(string requestUrl) : 
   3:          base(requestUrl, true) {
   4:          ...
   5:      }
   6:  }

After this you will be able to use MyDataContext in order to query data from the list from different site collection.

No comments:

Post a Comment