Introduction to Linq to SharePoint

Introduction to Linq to SharePoint

LINQ is a way to access external data sources.SharePoint Foundation 2010 comes with its own LINQ to SharePoint provider.
The namespace which contains the provider is Microsoft.SharePoint.Linq.dll.

LINQ provides strongly typed classes, this is an advantage of LINQ over CAML query.
Another advantage of LINQ is that Visual Studio provides IntelliSense to help in writing a query where as CAML Query is written in a string of text which will be executed only at runtime.

Overall we can say that LINQ provides more readable syntax than CAML.

As LINQ provides strongly typed classes, so SharePoint List must be strongly typed. This can be done by command line tool SPMetal.exe.

SPMetal.exe generate a class file which contains details about the list such as columns, content types, and other information.

SPMetal.exe is available in bin folder within hive folder of SharePoint.

Syntax to work with SPMetal is :

> “C:Program Files…14bin” SPMetal /web:http://spserver/sites /code:Site.cs /namespace:SP.Cafe.Linq

So above command will create entity classes for each list and library in the site and one DataContext class.

Now it’s time to access Site Data using LINQ.

First, create a DataContext class which is a part of Microsoft.SharePoint.Linq namespace. To access site data use below code.

DataContext dctxt = new DataContext(“Site URL”);

Pass list entity type to DataContext object to get a list object.
List object that’s returned has a type of EntityList<T>, where T is the type of object in the list.

Suppose your list name is Employee then overall code will look like this:

using System.Linq;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Linq;
DataContext dctxt = new DataContext(“Site URL”);
EntityList<Employee> emp = dctxt.GetList<Employee>(“Employee”);
var empData = from employee in emp select new {EmployeeName = employee.Title};
Gridview1.DataSource = empData;
Gridview1.DataBind();


In next blog, i will post the practical of this blog with the screen shot.

Leave a Comment

RSS
YouTube
YouTube
Instagram