Thursday, February 19, 2015

LINQ to SharePoint to seek name

One of the good feature of LINQ is to provide functinality to interact with SharePoint. LINQ is not only to "query" SharePoint list but also to provide CRUD operation on SharePoint list (known as LINQ to SP)

Noteworthy:

  • LINQ to SharePoint queries are translated to proper CAML queries
  • CAML queries are in turn later translated to SQL queries


Technically, the purpose of LINQ to SP is to replace the weird syntax of CAML query and provide user with Object Oriented way to do operations with SharePoint which is much easy to read / code and allow intelligence in Visual Studio during debug which was not feasible while working with CAML.

Lets begin with simple example.

Employee List


Here, I have created 1 example with employee list. We will write LINQ to SharePoint code to retrieve employee with name "Yagnesh".

Note: Use SPMetal exe which will generate Entity classes for DataContext. Get more info. on SPMetal here. If not, then developer has to create and decorate classes and its property by him self.

EmployeeEntitiesDataContext dc = new EmployeeEntitiesDataContext("http://ram:40705/sites/site1/");
EntityList<EmployeeItem> emp = dc.GetList<EmployeeItem>("Employee");
var updatedResult = (from empToUpd in emp
                                 where empToUpd.FirstName == "Yagnesh"
                                 select empToUpd).First();

First, we need to retrieve Data Context object. Data context object represent subset of content database which holds and work on list and list items.

EmployeeEntitiesDataContext dc = new EmployeeEntitiesDataContext("http://ram:40705/sites/site1");

Then, Getting reference to the list:

EntityList<EmployeeItem> emp = dc.GetList<EmployeeItem>("Employee");

EntityList<> Generice class is use to get any type of list available in SharePoint. Note, EmployeeItem is the class which represent all fields in Employee list.

Finally, LINQ query to seek employee name "Yagnesh".





1 comment:

  1. I read a article under the same title some time ago, but this articles quality is much, much better. How you do this..
    SharePoint ticketing system

    ReplyDelete