Saturday, 20 June 2015

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 provide Intellisense to help in writing query where as CAML Query is written in 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 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...\14\bin\" 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 its time to access Site Data using LINQ.

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

DataContext dctxt = new DataContext("Site URL");

Pass lists's 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;

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

No comments:

Post a Comment