PostRank Topblogs 2009 - #20 in Sharepoint

Windows Live Alerts web tracker
Chat with me if I'm online!
search blog
most popular
MCP MCTS MCT MVP

SP 2010: Getting started with LINQ to SharePoint in SharePoint 2010 

Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren

Introduction

In SharePoint 2010 you now have the ability to use LINQ syntax to fetch items from your lists instead of using the "traditional" approach of CAML queries. (Including SPSiteDataQuery and SPQuery objects)

In this article I will give you a brief introduction to how you can get started using LINQ queries in SharePoint, also known as LINQ to SharePoint.

Basics of LINQ?

As a prerequisite to this article, I'm going to imply that you know what LINQ is and how to write basic LINQ queries in any .NET application already. I'm not going to dive into the details about LINQ or the syntax itself here - please see MSDN for that!

LINQ to SharePoint!

In order to work with LINQ in SharePoint 2010, we need use a tool called SPMetal.exe which resides in the 14\bin folder. This tool is used to generate some entity classes which Visual Studio 2010 can use to get IntelliSense, and allows for LINQ-based queries to be performed on your lists.

Noteworthy:

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

SPMetal.exe

Using the tool called SPMetal, we generate our entity-classes that are needed to perform these object oriented queries toward our SharePoint server.

These are the required steps to get hooked up:

  1. Launch a cmd-window and navigate to C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\bin
    image
  2. Run the following command to utilize the SPMetal.exe tool with the following syntax:
    1. SPMetal.exe /web:http://yoursite /code:C:\YourEntityFile.cs
    2. Example:
      image
  3. Now navigate to C:\ (or wherever you chose to output your file) and make sure the file has been generated:
    image
  4. Open up the file and take a look at the content that SPMetal now have provided us with:
    image
    Note that the class name is now MyEntitiesDataContext. It's based on the name you specify as your code file in the SPMetal.exe command line tool.

    If you were to use /code:C:\Awesome.cs instead, it would generate a class called AwesomeDataContext.

With that done - all we need to do is import it to one of our projects and use it!

Visual Studio 2010 - Let's create a sample Web Part that utilizes LINQ to SharePoint

In this sample I will create a simple Web Part that will use LINQ to SharePoint syntax to fetch some information from the Announcements list. A basic sample I use in my training classes as well, and should be fairly easy to grasp!

  1. Create a new project (I'm going to create a new Visual Web Part project)
  2. Import your DataContext-file by choosing your Project -> Add -> Existing Item:
  3. Specify your file (mine is called MyEntities.cs):
  4. Make sure it's properly placed in your project structure - then we're good to go:
    image

Alright - that's easy enough. Thus far we have created an entity file using SPMetal.exe and now we have successfully imported it into our project.

Add proper references

Now in order to use LINQ to SharePoint, you also need to reference the Microsoft.SharePoint.Linq assembly. Point to references, right-click and choose "Add Reference" and select the Microsoft.SharePoint.Linq.dll file:
image

In your code, reference the assemblies:
image

Ready to code?

What you should've done up until now is this:

  1. Generate your entities using the SPMetal.exe tool
  2. Reference the newly created file from your SharePoint project
  3. Make sure you're using the proper references for System.Linq and Microsoft.SharePoint.Linq
  4. Be ready to code :-)

Code!

In my example I will have a Visual Web Part that will use LINQ to SharePoint to fetch all Announcements from my Announcement-list and work with those results. If you want to see the entire project, look at the bottom of this article where you can download it.

image

IntelliSense!

While you code your queries using LINQ to SharePoint, you will now have access to IntelliSense, which you did not have with CAML queries:
image

I'm going to leave it at that - very (very) easy to get started with LINQ to SharePoint, and all you really need to know is to start using the SPMetal tool to generate your entity classes and hook'em up with Visual Studio to start coding.

Summary & Download

As you can see, there's not a lot of things you need to do in order to work with LINQ in your SharePoint applications with your SharePoint-data.

I've been pinged plenty of times on how you can get started with this, and there you have it. More in-depth articles to come later - this is just to get your wagon rolling!

To download the sample project, click here: [Download]

Enjoy!

 
Posted on 19-Feb-10 by Tobias Zimmergren
14 Comments  |  Trackback Url  |  Link to this post | Bookmark this post with:        
Tags: 2010, How To, LINQ, LINQ to SharePoint, SP2010
 

Links to this post (Trackbacks/Pingbacks)

Comments

Friday, 19 Feb 2010 08:43 by Greg
never got around to do this yet - great and easy-to-understand introduction tobias. love that there now is intellistense in the vs code view instead of having to use caml query builder :)

Saturday, 20 Feb 2010 10:59 by Stephen Hodge
Hi Tobias. Thank you for the sample project.

Sunday, 21 Feb 2010 09:30 by khaled Abed
That's very nice, but I used LINQ to sharepoint 2007 also, but the performance is a weekness point in it. CAML Query translate to SQL direct but LINQ translate to CAML then to SQL.

Wednesday, 10 Mar 2010 10:21 by loogares
Hi, first off i would like to thanks for the code so we can take an earlier look of how it should look like should be done, i had a lil trouble with the solution, when deploying, i've got an error saying: The IsSafeAgainstScript attribute is not declared, but as a fact i am seeing it to true in the sharepointProjectItem.spdata, do you have any suggestion for this particular issue? Thank you very much in advance.

Thursday, 20 May 2010 06:05 by Gary
is it possible to use this for sharepoint 2007?

Tuesday, 1 Jun 2010 06:43 by Ramesh
Hi I am Ramesh Your done excellent Article thanks for giving this one. I have worked on your given article “ HOL1_Manual_cs“ While working on Linq and Share point topic. I need run these commands : set path=%path%;c:\program files\common files\microsoft shared\web server extensions\14\bin spmetal.exe /web:http://intranet.contoso.com /namespace:SPCHOL200_Ex1.VisualWebPart1 /code:SPLinq.cs First Command has run successfully. While run IInd one SPlinq.cs file has generated automatically but with in scan’s it will gone and then show error like below: Error : The Web application at http://intranet.contoso.com could not be found. Verify that you have typed the URL Correctly. If the URL should be serving existing content, the system administrator may need to add a new request URL mapping to the intended application. Can you please help me on this Thanks for your great help Ramesh :)

Monday, 21 Jun 2010 03:05 by Patty
I'm wondering why SPSecurity.RunWithElevatedPrivileges is not supported with Linq2SharePoint. Or it's only me who can't find out how to use it?

Monday, 5 Jul 2010 12:16 by Gautam
When I run the SPMetal command,I get this error: Feature "feature-id" for list template '10000' is not installed in this farm.The operation could not be completed. Any ideas why this is happening?

Tuesday, 6 Jul 2010 03:12 by
Hi Ramesh, I faced the same prob, then i use the below systax which contains the user credentials, SPMetal /web:http://ContosoServer/Marketing /code:MarketingSite.vb /user:Contoso\sally /password:7Yj38d -Saro,

Tuesday, 6 Jul 2010 03:13 by Saro
Hi Ramesh, I faced the same prob, then i use the below systax which contains the user credentials, SPMetal /web:http://ContosoServer/Marketing /code:MarketingSite.vb /user:Contoso\sally /password:7Yj38d

Wednesday, 7 Jul 2010 08:15 by Deepak
The spmetal.exe command is getting excecuted but the .cs file is not getting created

Wednesday, 21 Jul 2010 07:28 by Sudhir Kesharwani
This is a fantastic step by step tutorial. Just make sure to specify the output path between double quotes. Make sure you dont leave any space between /web:

Wednesday, 21 Jul 2010 05:17 by Sp
Does Metal exce support ContentType full html column?

Thursday, 22 Jul 2010 07:59 by Sp
Does Metal exce support ContentType full html column?

Name:
URL:
Email:
Comments: