LINQ to SharePoint with SharePoint 2010

With SharePoint 2010, LINQ to SharePoint is now fully supported. It now offers the ability to work with strongly typed objects as well as the ability to use the LINQ syntax which is easier than using CAML. Another great advantage of using LINQ to SharePoint is that you can join SharePoint lists which can be very powerful.
In order to use LINQ to SharePoint, you will need to have entity classes created. Rather than having to create them manually which would take a long time, Microsoft provided a small utility that creates all those objects for you called SPMetal (click here for more information). The SPMetal utility works similarly to the SQLMetal utility (extracts SQL metadata from a database and generates entity classes). SPMetal will generate those entity classes which are used in LINQ to execute SharePoint queries. When those queries are executed, the LINQ statements are in turn translated to CAML.
SPMetal command syntax

SPMetal.exe /web:http://yoursite/ namespace:LINQtoSharePoint /code:SPLinq.cs

  • web: The complete, absolute URL of the Web site whose data is modeled by the entity classes.
  • namespace: The namespace that contains the entity class declarations.
  • code: The relative or absolute path and file name of the output file.

For more command line options, see here.
After the command was successfully executed with SPMetal, code should have been created for you:

Add that code to your SharePoint project.

Notice that a class ‘SPLinqDataContext’ is created by the SPMetal tool containing all the lists available within the SharePoint site.

All those SharePoint lists can now be queried using the SPLinqDataContext class.

Now you can use the LINQ syntax to query SharePoint data:

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

PointBridge Blogs

More from this Author

Follow Us