Thursday, August 27, 2015

SPMetal in Sharepoint 2013

SPMetal in Sharepoint 2013

What is SPMetal?

SPMetal is a command-line tool that generates entity classes, which provide an object-oriented interface to the Microsoft SharePoint Foundation content databases. These classes are primarily used in LINQ to SharePointqueries; 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?

To generate the entity class using SPMetal:

Step 1

Go to the path
C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\BIN
Open command Window here:
 

Step 2

Run the command here:
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 entity class file generated.

Different Command Line Options

Here, http://msdn.microsoft.com/en-us/library/ee538255.aspx mentions the different command line options forSpmetal.

Using in Visual Studio

When you are creating an application using this entity class, you need to add the referenceMicrosoft.Sharepoint.LINQ.
In code behind of Webpart, add the following namespaces:
using System.Linq;
using Microsoft.SharePoint.Linq;
using Microsoft.SharePoint;

Insert a value to “Country” List

Create a list in SharePoint and insert a value through VS2012 console application:
 
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:

No comments:

Post a Comment