SPMetal in Sharepoint 2013

What is SPMetal?

SPMetal is a command-line tool that generates entity classes, that provide an object-oriented interface to the Microsoft SharePoint Foundation content databases. These classes are primarily used in LINQ to SharePoint queries, but they are also used to add, delete, and change list items with concurrency conflict resolution. Finally, they can be used as an alternative to the regular SharePoint Foundation object model for referencing content.

How to Use SPMetal?

Generate an entity class using SPMetal.

Step 1: Go to the path

C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\BIN

Open a command window here:

SPMetal1.jpg

Step 2: Run the command here

SPMetal2.jpg

C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\BIN>Spmetal.exe /web: http://Your Site/ /code: [File location to save]/Myentitycontext.cs

After that the entity class file is generated.

SPMetal3.jpg

The various command line options for SPMetal are specified in: http://msdn.microsoft.com/en-us/library/ee538255.aspx.

SPMetal4.jpg

Using in Visual Studio

When you are creating an application using this entity class, you need to add the reference "Microsoft.Sharepoint.LINQ".

In the Code Behind of the Webpart, add the following namespaces:

using System.Linq;
using Microsoft.SharePoint.Linq;
using Microsoft.SharePoint;

Inserting a value into the "Country" List

Create a list in SharePoint and insert a value using a Visual Studio 2012 console application, as in the following:

SPMetal5.jpg

using (MyentitycontextDataContext myEntity = new MyentitycontextDataContext("http://sptest:1001"))

            {

 

                CountryItem myCountry = new CountryItem();

                myCountry.Title = "My Country1";

                myCountry.CountryName = "USA";

                myEntity.Country.InsertOnSubmit(myCountry);

                myEntity.SubmitChanges();

              

            }

Now refresh the site; the value is inserted, as in the following:

SPMetal6.jpg

References

http://msdn.microsoft.com/en-IN/library/ee538255(v=office.14).aspx
http://msdn.microsoft.com/en-in/library/ee537010.aspx
http://www.pranavsharma.com/blog/2011/12/16/large-list-performance-spmetal-vs-spquery/

Summary

In this article I tried to explain how to create an entity class and use it for Read, Insert, Update, and Delete using LINQ to SharePoint.
 

Up Next
    Ebook Download
    View all
    Learn
    View all