Linq to SharePoint 2013

This SharePoint tutorial, we will discuss how to use Linq to SharePoint 2013 and also, we will discuss how to use linq to insert item to SharePoint 2013/2016 list.

The LINQ to SharePoint Provider is defined in Microsoft.SharePoint.Linq namespace. It translates LINQ queries into Collaborative Application Markup Language (CAML) queries. It is no longer necessary for developers to know how to write CAML queries. LINQ queries can be used in server code.

To work with LINQ, we need to have data context and LINQ classes. For this, we can use SPMetal.

SPMetal is a command-line tool that generates entity classes and these classes are used in LINQ to SharePoint queries and also used to add, delete, and change list items with concurrency conflict resolution.

SPMetal.exe is presented in the below location:

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

The SPMetal took parameter is like below:

Spmetal.exe /web:http://mypc:29024/sites/SPTraining /code:"E:\MySPMetalEntity.cs"

The whole command looks like below:

E:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\BIN>Spmetal.exe /web:http://mypc:29024/sites/SPTraining /code:"E:\MySPMetalEntity.cs"
Linq to SharePoint 2013
Linq to SharePoint 2013

Once the command successfully executed it will create a MySPMetalEntity.cs class.

Now it is time we will use the class in our visual web part in SharePoint.

First, we need to create a visual web part. For this, you can follow our previous section where we have discussed how to create visual web part.

Once you create the SharePoint visual web part.

Now we need to give reference to Microsoft.SharePoint.Linq. The dll is available in the below directory.

E:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI

Here E drive is where I have installed SharePoint 2016.

After giving reference to the Linq dll, Add the .cs file which we have generated above by using SPMeta.exe. Right click on the project -> Add Existing Item and you can add the class.

Now if you will open the solution explorer, it should look like below:

Linq to SharePoint 2016
Linq to SharePoint 2016 and Linq to SharePoint 2013 examples

Now we will design the interface as well as the code:

Enter Name: <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:Button ID="btnAdd" runat="server" Text="Add Item to Employee List" OnClick="btnAdd_Click" />


protected void btnAdd_Click(object sender, EventArgs e)
MySPMetalEntityDataContext myEmpEntiry = new MySPMetalEntityDataContext("http://mypc:29024/sites/HydTraining/");
EmpItem myEmpItem = new EmpItem();
myEmpItem.Title = txtName.Text;

Now deploy the visuals web part and then add the web part to a web part page in SharePoint. Now if you will save an item it should save.

You may like following SharePoint tutorials:

This is how we can work with Linq to SharePoint 2013 example.