Tuesday, January 18, 2011

SharePoint LINQ Support

With SharePoint 2007, we had to use CAML queries to write queries against the server, using the SPQuery or SPSiteDataQuery objects. You would write your CAML as a string and pass it to those objects, so there were no strongly typed objects or syntax checking as part of the API.  Instead, you would either have to cross your fingers that you got the query right or use a third-party tool to try to generate your CAML queries.  To make this easier, SharePoint 2010 introduces SharePoint LINQ (SPLINQ).  By having a LINQ Provider, 2010 allows you to use LINQ to write your queries against SharePoint in a  strongly typed way with Intellisense and compile-time checking.   Under the covers, the SharePoint LINQ provider translates your LINQ query into a CAML query and executes it against the server.  As you will, you can retrieve the CAML query that the LINQ provider generated to understand what is being passed back to the server.

Sample code in old  days:

SpSite site = new SpSite(http://samlehome.com/);
SpWeb web = site.openweb();
List<SPList> hiddenLists = new List<SPlist>(); // Do not use an SPListCollection here
foreach (SPList list in web.Lists){
if (list.Hidden)
hiddenLists.Add(list);

}
Notice number of lines of code with LINQ:
SPSite site = new SPSite("http://samlehome.com");SPWeb web = site.AllWebs[0];var hiddenLists = from list in web.Lists where list.Hidden select list;

Getting Started with SharePoint LINQ: SPMetal
The first step in getting starting with SPLINQ is generating the entity classes and properties for your lists. Rather than writing these by hand, you can use the command-line tool that ships with SharePoint, called SPMetal.  SPMetal will parse your lists and generate the necessary classes for you that you can import into your Visual Studio projects.  You can find SPMetal at %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\14\bin.  You can run SPMetal from the command prompts, but if you prefer, you can write a batch file that you have Visual Studio run as part of your pre-build for your project so that the latest version of your entity classes are always included.
Using SPMetal is straightforward for the common scenarios that you will want to do.   It does support XML customization, but most of the time you will find that you do not need to customize the default code generation.
SPMetal command line parameters:http://msdn.microsoft.com/en-us/library/ee538255.aspx
Once you generated the file and included in your Solution you can easily create SPLINQ applications.
This is just a small example:
One thing that you may realize is that SPMetal, by default, does not generate all the fields for your content types.   So, you may find that fields such as Created or Modifiedby do not appear in the types created by SPMetal.  To add these fields, you can specify them in a Parameters.XML. 

No comments:

Post a Comment