Answered Unable to acces lists cross site collection using Linq To SharePoint

  • Friday, January 08, 2010 12:11 PM
     
      Has Code
    I'm currently developing a 2010 webpart project, where I query 3 lists on 3 different site collections.

    I query these list from a webpart that is located on the root site collection: http://portaltest

    Site col 1: http://portaldev/sites/site1 - list x
    Site col 2: http://portaldev/sites/site2 - list y
    Site col 3: http://portaldev/sites/site2 - list z

    When I try to access list x on the site collection: http://portaldev/sites/site1 (from a webpart on the root site collection http://portaldev)
    I receive an ArgumentException: {"Web at http://portaldev/sites/site1 could not be found"}

    The code that I am using is the folowing
     using (LinqDataContext ctx = new LinqDataContext("http://portaldev/sites/site1"))
     {
         EntityList<listx> entities = ctx.GetList<listx>("listx");
     }
    


    But when I try to run the same webpart on a web of http://portaldev/sites/site1, the code will run an I'm able to query the list x.

Answers

  • Tuesday, January 19, 2010 3:43 PM
     
     Answered Has Code

    We have found a workaround by changing the SPContext before executing the LINQ query.

    In the webpart itself the HttpContext is stored in a variable before executing our search method.

    SPSecurity.RunWithElevatedPrivileges(delegate()
    {
         using (SPSite contextSite = new SPSite("http://<URL>"))
         {
              using (SPWeb contextWeb = contextSite.OpenWeb())
              {
                   HttpRequest httpRequest = new HttpRequest("", contextWeb.Url, "");
                   HttpContext.Current = new HttpContext(httpRequest, new HttpResponse(new StringWriter()));
                   SPControl.SetContextWeb(HttpContext.Current, contextWeb);               
                   using (MyLinqDataContext dc = new MyLinqDataContext("http://<URL>"))
                   {
                        EntityList<MyEntity> entities = dc.GetList<MyEntity>("<ListName>");
                        {
                        }
                   }
               }
         }
    }
    After performing the search we set the HttpContext back to the original HttpContext.


    tempContext = HttpContext.Current;
    this.Search();
    HttpContext.Current = tempContext;


    I'm not sure if this workaround is appropriate, but at least we can now perform our cross site collection LINQ query in our webpart :)

    Regards,
    Pascal

All Replies