Basics: Interact with SharePoint 2010 Data (post 3 – SPMetal and LinQ)

This is the third tutorial about accessing and manipulating data on SharePoint. The first one leveraged web services and the second used the server object model. There’s a client object model as well, but we’ll see more about that some other time.

In order to leverage LINQ, you will first need to create a strongly typed entity model of your SharePoint site. You can achieve this easily by using a utility found in the /bin folder of your SharePoint root.

c:\program files\common files\microsoft shared\web server extensions\14\bin

Once you have accessed the folder, you will find the application SPMetal. In order to create the strongly typed entity model that you will use with LINQ, you need to run the following:

SPMetal  /web:<your site collection URL> /code:<the name of the file you want to create with a .cs extension> /language:csharp

That will create a .cs file for you. You will need to reference that file in your Visual Studio code. Lets do that now.

1. Start an empty SharePoint project, reference the .cs file that you just created and also, add another reference to Microsoft.SharePoint.Linq
2. Add a new item, a web part. Add a “using Microsoft.SharePoint.Linq” directive to the new web part.
3. You need to add an SPEntityModelDataContext. Do it as follows:

using (SPEntityModelDataContext dataContext = new SPEntityModelDataContext(“<your site collection URL>”))

4. You will then need to fetch your data from SharePoint. Easily do that as if you  were doing a SELECT * statement in SQL:

var namedVariable = from data in dataContext.nameOfYourList select data;

5. You can now easily access the items in your nameOfYourList list. For example, if you had wanted to pass values to a listbox, you would:

foreach (var item in namedVariable) {
listboxName.Items.Add(item.Title.ToString()); }

and that would add all the titles of the items in your list, into your listbox.

 

MGR: the Intelogist

About MGR: the Intelogist

SharePoint Server developer, turned Sitefinity developer, turned Angular developer, turned SharePoint Online consultant, turned Unily consultant, turned O365 consultant... Never a dull moment!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> 

This site uses Akismet to reduce spam. Learn how your comment data is processed.