Using SPMetal in SharePoint 2010

Published on
-
2 min read

One of the best development features in making customisations within a SharePoint environment is the SPMetal tool. The SPMetal tool generates entity classes in order to use LINQ syntax to retrieve items from lists. The SPMetal.exe resides in the 14/bin folder. I will show you a quick demonstration on how I have generated a DataContext class using the SPMetal executable.

You will need to create two files:

  1. XML file – containing the list or library name we are interested in generating our class from. In the code snippet (below), the list I am interested in is called Quicklinks.
<?xml version="1.0" encoding="utf-8"?>
<Web xmlns="http://schemas.microsoft.com/SharePoint/2009/spmetal">
  <List Name="Quicklinks" Member="Quicklinks" />
  <ExcludeOtherLists />
</Web>

Save the XML file into the 14/bin director and name it “SPMetalConfig.xml”.

  1. Batch File – will contain the SharePoint command prompt needed to fire the SPMetal executable. Creating a batch file is not required. You can run the command as normal through Windows Command Line. I just find it a lot easier to manage and make changes using a batch file.
SET SPMETALDIR="C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN\" 

cd %SPMETALDIR% 

spmetal.exe /web:http://myintranet /code:QuicklinksOMEnitites.cs /parameters:SPMetalConfig.xml

Once this has run, a class called “QuicklinksOMEnitites.cs” will be generated in the 14/bin folder.

SPMetal.exe

One thing I did find when using SPMetal for retrieving list data to be output to a custom webpart was that it is only able to retrieve data from a site collection the list resides. But this is probably to be expected. So if the webpart was used in a separate site collection, no data will be shown. In order to get around this, SPMetal will not suffice. You will need to go through the code route and do the following:

SPSecurity.RunWithElevatedPrivileges(delegate()
{
    using (SPWeb intranetSite = new SPSite("http://myintranet/sites/depts/").OpenWeb())
    {
        SPList quickLinks = intranetSite.Lists.TryGetList("Quicklinks");
        
        if (quickLinks != null)
        {
            //Do something with list data.
        }                           
    }
}); 

Before you go...

If you've found this post helpful, you can buy me a coffee. It's certainly not necessary but much appreciated!

Buy Me A Coffee

Leave A Comment

If you have any questions or suggestions, feel free to leave a comment. Your comment will not only help others, but also myself.