Tuesday, March 5, 2013

SharePoint 2010 : Query using SPMetal entity

In SharePoint 2010, we can use LINQ queries to search data within SharePoint site. In previous SharePoint versions, I tend to use CAML queries instead, which is an efficient way to look for items. However, LINQ queries are faster and simpler to implement.
For more information on LINQ queries: follow this URL
For using LINQ within SharePoint, Microsoft has provided a tool named SPMetal.exe which resides in the 14 hive folder. This tool generates an entity class which we can add to our Visual Studio solution to get intellisense and use the entity classes for fetching data from SharePoint site.

Using SPMetal.exe

Go to command prompt and navigate to
  • C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\bin
  • Type SPMetal.exe /web:http://sharepointsite /code:C:\MyLINQEntity.cs

Now if you open the file, we just created, you can see all the lists, libraries have their classes with content types mentioned. It might happen that some custom content types are replaces with Item which is by default behaviour; you can modify the content types for the actual ones (you will get it in the intellisense).

Now that you add your .cs file to your Visual Studio project, you can use it for fetching items in SharePoint site.

using (PropertiesEntityDataContext context = new PropertiesEntityDataContext(SPSiteAddress))
{
//creating object from the Entity
EntityList<legalcasedocumentset> documentSet = context.GetList<legalcasedocumentset>(libName);
var first3Items = from item in documentSet.ScopeToFolder(folderURL, true)
where item.Name == docSetName
select item;

No comments: