LINQ to SharePoint and RunWithElevatedPrivileges

Recently we were working with LINQ to SharePoint Web Part for anonymous users and faced an issue with elevated permissions.
Web Part has query through LINQ to a custom list for which currently logged in user (logged in user is anonymous user) does not have access so Web Part runs with elevated privilege but it was not working.

Reason: LINQ seems to build some “context” even before the Web Part runs with Elevated Privileges so that it throws an exception says that list “yourlistname” is not available/found.

Code with Problem:

Findings: It was an interesting issue, after researching I found that it was because of a constructor which call in the class SPServerDataConnection class within the Microsoft.SharePoint.Linq.dll

Lawbreaker: Microsoft.SharePoint.Linq.Provider.SPServerDataConnection class

Background Process: When we create a new instance of SharePoint Linq DataContext it actually executes a constructor of SPServerDataConnection class where some funny things happening in behind. If we are executing the code with SPContext then it will be using the SPSite and SPWeb instances under the current context and because of that we were getting an exception.

The issues was how to find internal code of SPServerDataConnection, so i used Reflector and got that as below:

Solution: After reviewing SPServerDataConnection code we found that we can tweak this functionality by creating a new HttpContext and use it under elevated permission to execute our code. After our usage set the actual SPContext back.

Sample Web Part code given below

NOTE: Make sure that you are setting the actual SPContext back after your operation.

Hope this will help!!!


  1. I’ve learn several just right stuff here. Certainly worth bookmarking for revisiting. I wonder how a lot effort you put to create this kind of fantastic informative site.

  2. Hello there! This post couldn’t be written much better! Looking through this article reminds me of my previous roommate! He continually kept talking about this. I will send this article to him. Fairly certain he’ll have a good read.

    I appreciate you for sharing!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s