How to access a List using Linq to Sharepoint

Linq to Sharepoint is actually a thin layer that converts your Linq queries to CAML queries. But hey, Linq is much more expressive, so I choose productivity over small performance gain :)

Here are the steps to accomplish that:

 

1. Create an XML file named “myList.xml” . It contains this:

<?xml version="1.0" encoding="utf-8"?>
<Web AccessModifier="Internal" xmlns="http://schemas.microsoft.com/SharePoint/2009/spmetal">
  
<List Name="MyListName" />
    
<ExcludeOtherLists />
</Web>

 

‘Cos by default, the tool will generate DataContext for _all_ lists , and you don’t want that. The .xml config will only generate DataContext for “MyListName”

 

2. Open a Command Prompt, add this folder “C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN” to your current path:

> SET PATH = %PATH%;C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN

 

3. Now run the SPMetal tool (the equivalent of DBMetal for Linq to SQL)

> SPMetal /web:http://localhost /namespace:MyProject.DataContext /code:MyListName.cs /parameters:myList.xml

 

4. Use Visual Studio 2010 to Add Existing Item and include the generated MyListName.cs file.

 

5. Now from a Web Part, you can access this List with pure joyful LINQ expressions

// Query for unique Cities
using (var ctx = new MyListNameDataContext(SPContext.Current.Web.Url))
{
  ctx.ObjectTrackingEnabled = false; // performance-mode
  var someList = ctx.GetList<MyListNameContentType>("My List Name");
  var uniqueCities = (from p in someList
          select p.City).Distinct();
  foreach (var city in uniqueCities)
  {
    cityList.Items.Add(city);
  }
}
Share this post: | | | |
Published Monday, August 30, 2010 5:42 AM by zeddy
Filed under: ,

Comments

# Using jQuery to access Sharepoint List

Monday, August 30, 2010 1:04 PM by Z & his Startup

In my previous post I showed how to access a Sharepoint List using Linq , this time I want to show you

Powered by Community Server (Commercial Edition), by Telligent Systems