Step by Step – How to Use LINQ-to-SharePoint to query SharePoint List data efficiently

LINQ-to-SharePoint is most efficient way to query the SharePoint data into code using object oriented technologies.

References 

Step by Step Usage – 4 easy Steps

  • Step 1: Add Microsoft.SharePoint.LINQ Reference
  • Step 2: Use the SPMETAL to generate the LINQ-to-SharePoint Data Context Class

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN>spmetal.exe /web:http://sp2010vm /namespace:SandboxedSolution.ProjectDashboardSummary /code:SPProjectInitiation.cs

This will create the SPProjectInitiation.cs in the C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN and SPProjectInitiationDataContext as a Data Context. Please remember you have to regenerate this class every time you change the schema in the SharePoint Lists. 

  • Step 3: Add the LINQ-to-SharePoint Data Context Class (e.g. SPProjectInitiation.cs) in your Visual Studio Project
  • Step 4: Write the Queries against the SharePoint List

                SPProjectInitiationDataContext dc = new SPProjectInitiationDataContext(SPContext.Current.Site.Url);
                var query = from c in dc.BusITCapitalBudget
                            where c.Year.Equals(strYear)
                            select c;
 
                string strTargetCapitalBudget = "0";
                foreach (var c in query)
                {
                    strTargetCapitalBudget = c.TargetCapitalBudget == null ? "0" : c.TargetCapitalBudget.ToString();
                 } 

Maintenance Considerations

Advertisements
This entry was posted in SP2010 DEV General. Bookmark the permalink.