In WSS 3.0 and MOSS 2007 develpoers used CAML (Collaborative Markup Language) queries to querying SharePoint lists using SPSiteDataQuery and SPQuery objects. Now this becomes simple in SharePoint 2010 with the help of LINQ.

For querying LINQ we need Entity Classes which Visual Studio 2010 can use to get IntelliSense of SharePoint Lists. With the help of these entity classes we can interact with SharePoint Lists and Libraries. We can join two lists, apply where conditions, sort the items using order by and group the items. SharePoint 2010 provide a tool called SPMetal for generating the entity-classes that are needed to perform these object oriented queries. In this article I will present you the way to generate these entity-classes using SPMetal tool or how we can use SPMetal tool to generate entity-classes. 

Steps for Generating Entity-Classes

In order to generate entity-classes first we need to locate the tool called SPMetal.exe. Open the SharePoint 2010 hive directory (C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14). Goto bin folder and follow these required steps: 

  Launch a command prompt window and navigate to C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\bin as shown in Figure 1

Figure 1

  Run the following command to consume the SPMetal.exe tool with the following syntax (see Figure 2): 
     SPMetal.exe /web:http://om:1001 /code:C:\MySPEntityClass.cs

Figure 2

  Now navigate to C:\ (or wherever you chose to output your file) and make sure the file has been generated:

Figure 3

  Open up the MySPEntityClass.cs file and take a look at the content:

Figure 4

Entity class name is based on the name you specify as your code file in the SPMetal.exe command line tool. When you write the LINQ queries using this entity class file, queries are translated to accurate CAML queries and CAML queries are in turn later translated to SQL queries

Now you only need to import it to your project and use it like below mentioned code:

using (MySPEntityClassDataContext ILEntitiesDataContext = new MySPEntityClassDataContext(SPContext.Current.Web.Url)) 
   commentsCount = (from myComment in ILEntitiesDataContext.MyComments
                     where myComment.CreatedBy == SPContext.Current.Web.CurrentUser.Name
                     select myComment.Id.Value).Count();



In this article you learned how to create Entity Class for using Linq to SharePoint. we should appreciate the power of LINQ to SharePoint 2010 after seeing the huge CAML block that we’ll need to otherwise construct and do this simple task.

Copyrights 2019,