Sunday, March 7, 2010

LINQ to SharePoint

Title: LINQ to SharePoint

Details: Its not new to us that LINQ to SharePoint is newly introduced in SharePoint 2010 with a new Provider 'Microsoft.SharePoint.Linq'. It translates LINQ Queries into CAML queries. Which means... bye bye CAML ( you can still use it if you love it ). Few pointers on LINQ to SharePoint...
  • No CAML required
  • Can be called against both server and client object model
  • Tools available ( SPMetal ) to create business layer ( entity classes ) - How to use SPMetal?
  • Intellisense helps query construction
  • Query across multiple lists with relationships
  • Allow inefficient queries
  • Merge results from multiple lists and multiple data sources
  • Join results from multiple data sources
Code: Sample code on how to use LINQ to SharePoint is as shown below. ( Code run against my custom list called FirstNames which has column name FirstName ). You need to create the entity class ( EntitiesDataContext in the below example ) first using SPMetal that would give a data context for our use.

DataContext data = new DataContext(SPContext.GetContext(this.Context).Web.Url);

using (EntitiesDataContext moEntitiesDataContext = new EntitiesDataContext(SPContext.GetContext(this.Context).Web.Url))
    var fn = from fNames in moEntitiesDataContext.FirstNames
            select new { fNames.FirstName };                    

No comments: