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 14bin 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 FilesCommon FilesMicrosoft SharedWeb Server Extensions14bin
    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!

Follow me

Tobias Zimmergren

Founder / Consultant / Advisor at TOZIT AB
Tobias Zimmergren delivers high-quality articles about business and technology around the Microsoft scene.

Tobias focuses on advisory and consultancy for the Office 365 and SharePoint offerings from Microsoft.
Follow me
  • Kristopher Baker

    Download link is broken?

    • http://www.zimmergren.net/ Tobias Zimmergren

      Kristopher ,

      The download link broke when I migrated from the old blog. Just follow along with the article and you’ll have the exact same result as if you were to download the sample project.

      Cheers,
      Tobias.

  • Mahaa Karthik

    when i run the spmetal.exe am getting one error like must specify the souce code language..please resolve this issue..

    • http://www.zimmergren.net/ Tobias Zimmergren

      Hi Mahaa,

      That’s an issue on your end, and not something anyone over here can fix for you – especially when you don’t provide any more details than what you did.
      Check the logs for hints and do a search online for the error message. SPMetal.exe is a working command line tool that comes with SharePoint, so if you encounter errors it’s most likely something with your environment.

      Cheers,
      Tobias.

      • Mahaa Karthik

        Thank you Zimmergren

        • http://www.zimmergren.net/ Tobias Zimmergren

          You’re most welcome.
          Did you sort it out yet? Otherwise try attaching screenshots and logs of the errors.

          Cheers,
          Tobias.

      • Fuckyou

        You were very unpleasant. Are you Microsoft MVP?? my god…

  • Richardscannell

    Does the work with a remote c# application, or does it need to be on the sharepoint server?

  • Sureshtg050

    Thanks a lot for sharing this Article.its really good for beginners who wants to use LINQ in SHAREPOINT 2010.

    • http://www.zimmergren.net/ Tobias Zimmergren

      Cheers mate.

  • Pingback: Extending the LINQ to SharePoint context to allow additional fields and properties in your queries | Tobias Zimmergren's thoughts on development()

  • Harshdamania123

    i am facing a problem with my linq code,It gets executed when a person has full control.

    • http://www.zimmergren.net/ Tobias Zimmergren

      Please elaborate a bit more. Perhaps you’ll need to elevate the privileges of your executing code using the SPSecurity.RunWithElevatedPrivileges() method?

  • Ted

    Download link not working Tobias.

    Thanks,
    -Ted

    • http://www.zimmergren.net/ Tobias Zimmergren

      Hi Ted,

      Thanks for the heads up. Unfortunately I lost the files when I migrated my blog to the new platform. I forgot to copy the downloads-directory ;-)

      Regards,
      Tobias.

  • rani priyanka

    Its a nice article very nicely explained especially for beginners like me.Is there another way to have a look at the code or a download link.

    • http://www.zimmergren.net/ Tobias Zimmergren

      Thank you. Unfortunately I lost the files when I migrated my blog to the new platform, so you’ll have to reproduce the steps instead.
      Cheers,
      Tobias.

  • Sebastian Greco

    thanks man for sharing this kind of information and knowledge, Im a asp.net developer and Im trying to do something on Shsrepoint, This article hepls me a lot to understand and improve the linq functionality in my project.

    • http://www.zimmergren.net/ Tobias Zimmergren

      Hi Sebastian,
      Thank you for your comment – I appreciate it, and I hope you’re on track in your endeavours to learn SharePoint :-)

  • Kien Dinh

    Thanks for your article. But when i try this, i met an error message: System.InvalidOperationException: The query uses unsupported elements, such as references to more than one list, or the projection of a complete entity by using EntityRef/EntitySet.

  • Shaun English

    Nice article, quick question to see if what I’m trying to do is possible. I have a formView to display an item from a sharepoint list. I’ve used a LinqDataSource control to query my DataContext and then I display the information returned in the formView.

    However, I’m now trying to perform an update using the formView edit template and I keep getting an error when I click update. (The data context must extend DataContext when the Delete, Insert or Update operations are enabled). Is what I’m trying to do not possible? I’m guessing the error is down to my Linq to Sharepoint datacontext extending Microsoft.SharePoint.Linq.DataContext and not System.Data.Linq.DataContext?

    Thanks,
    Shaun

  • Maggie

    Hello thanks for posting but I haven’t been able to run this. From where pnlAnnouncements comes from? it is not recognized in my code. Also, AnnounmentItem. I will appreciate your help. Thanks

    • http://www.zimmergren.net/ Tobias Zimmergren

      Hi Maggie,
      The AnnouncementItem is a class I created myself just for the sample. You can see in the code that what you really need and want is the a.Title, a.Body and so on. The pnlAnnouncement is an ASP.NET Panel in my Visual Web Part, something you’d have to add yourself to your control :-)

      I hope that helps.
      Tobias.

      • Maggie Gouveia

        Thanks a lot for answering, it did helped.

        I dragged the panel on my visual web part and gave it this id: ‘pnlAnnouncement’ but it’s still not recognized in my Page_Load function.
        I try to google this but I’m afraid I’m not using the correct words. If you will want to find information about this, what will you type in google?

        Thanks again Tobias

        Your posting is excellent, very well organized.

        • http://www.zimmergren.net/ Tobias Zimmergren

          Hi Maggie,
          I’d suggest looking up how to add web controls to an ASP.NET web form. That’s essentially what we’re doing here.
          Cheers,
          Tobias

          • Maggie Gouveia

            Thanks again Tobias

  • Solo

    I am developing a SilverLight Web Part for SharePoint 2010 in C#. I have
    made a LINQ to SQL connection, and it works when I lunch the
    SilverLight alone.

    When I lunch SilverLight as a Web Part in SharePoint it does not work.

    What am I doing wrong?

    • http://www.zimmergren.net/ Tobias Zimmergren

      Hi Solo,
      That all comes down to what your code looks like of course – if you can paste the code somewhere I might be able to find out, but without the code there will be little success :)

  • Laura Quesada

    Thanks! This post was very helpful!

    • http://www.zimmergren.net/ Tobias Zimmergren

      Hi Laura and thank you.
      Cheers,
      Tobias.

  • john alex

    Hi Tobias your article is very Good.. How to use lookup columns in entity class.. Could you help help me please ASAP

  • Taras

    Hi,
    I’m new to Sharepoint codding, and I have a task to write a programm to get versions of every item in one of my lists(info should go to file). I managed to write a code, and it seems to be right. Question is what type of Visual Studio prject shoud I use to get it working, and what are my possible options?

    Regards

    • http://www.zimmergren.net/ Tobias Zimmergren

      Hi Taras,
      My first counter-question would be: If you already got it right and have the code written, don’t you also have a Visual Studio project for that?
      Choosing VS Projects are always based on your requirements of course, so if you have any specific requirements for how it should work – line them up and I can direct you in the proper direction :-)
      Cheers,
      Tobias.

      • Taras

        I mean I got a logic for getting info I need form my site and pushing it into file. I’d like it to be a console app that I would shedule to run once a day. Please let me know if may need any other details.
        Thanks

  • Pingback: SharePoint Developers Info » Extending the LINQ to SharePoint context to allow additional fields and properties in your queries()

  • Sandeep Kumar Vemula

    nice article… if possible give some examples with join’s

  • sri

    Thanks, Its works for me

    • http://www.zimmergren.net/ Tobias Zimmergren

      Cheers, glad I could help.

  • test

    How to get all BlogPosts with comments, posts, etc from a sharepoint site

    • http://www.zimmergren.net/ Tobias Zimmergren

      Hi “test”,

      Well, that depends on what you want to do, where you want to display them, how you want them presented etc. What’s the goal?

      Cheers,
      Tobias.