LINQ To SQL – CRUD Operations

We have seen a lot of articles on LINQ to SQL. Before going through this article, I would recommend to have some basic information about LINQ to SQL. Refer to these links for the same.

So, what is LINQ?

LINQ stands for Language Integrated Query. LINQ enables us to query any type of data store (SQL Server documents, objects in memory etc.).

I will not cover the details here in this article. You can read the complete article from the links mentioned above.

Let’s get started!!

We want to achieve this output.

We will create a simple example which is LINQ to SQL for CRUD operations.

First, create an empty application and give it a suitable name.

Now, let’s create a sample table called registration. Here is the script to create a table.

  1. USE [TEST]
  2. GO
  3. /****** Object:  Table [dbo].[registration]    Script Date: 1/16/2017 11:53:27 PM ******/
  4. SET ANSI_NULLS ON
  5. GO
  6. SET QUOTED_IDENTIFIER ON
  7. GO
  8. CREATE TABLE [dbo].[registration](
  9.     [id] [int] IDENTITY(1,1) NOT NULL,
  10.     [FirstName] [nvarchar](maxNULL,
  11.     [MiddleName] [nvarchar](maxNULL,
  12.     [LastName] [nvarchar](maxNULL,
  13.     [Address] [nvarchar](maxNULL,
  14.     [Landmark] [nvarchar](maxNULL,
  15.     [EmailID] [nvarchar](maxNULL,
  16.     [Country] [nvarchar](maxNULL,
  17.     [State] [nvarchar](maxNULL,
  18.     [City] [nvarchar](maxNULL,
  19.     [MobileNumber] [nvarchar](maxNULL,
  20.  CONSTRAINT [PK_registration] PRIMARY KEY CLUSTERED
  21. (
  22.     [id] ASC
  23. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]
  24. ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
  25. GO

Adding DBML File

Now, let’s add LINQ to SQL Class file. To do that, click on the Project ->Add New Items -> Data Tab,
select LINQ to SQL Classes, name it as “Sample.dbml”, and Click OK.

LINQ to SQL.

Now, open the Server Explorer in Visual Studio and locate the database that you created. After that, search for the table registration. Drag and drop the table on LINQ to SQL designer class.

When you drag and drop the table on LINQ to SQL designer, it will automatically create a business object for us. Here, sampledatacontext is our main file and the entry point or gateway of our application. The operations which we are going to perform like insert, update, and delete, will happen through this file. The Sampledatacontext will initiate the connection strings for us in web.config file.

So, the connection string here is.

GUI Part

Add a webform. Now, let’s setup the GUI part. First, we will include all the support files like bootstrap and jQuery.

  1. <link href=“Styles/bootstrap.css” rel=“stylesheet” />
  2.    “Scripts/jquery-1.8.2.js”>
  3.    “Scripts/bootstrap.js”>

These are supporting files for our application. We will be including a modal popup here. So first, drag and drop the Script Manager control on the form.

  1. <asp:ScriptManager runat=“server” ID=“ScriptManager1” />

Select Code

Now, let’s place the Grid View inside the UpdatePanel control.

  1. <!– Placing GridView in UpdatePanel–>
  2.             <asp:UpdatePanel ID=“upCrudGrid” runat=“server”>
  3.                 <ContentTemplate>
  4.                     <asp:GridView ID=“GridView1” runat=“server” Width=“940px” HorizontalAlign=“Center”
  5.                         OnRowCommand=“GridView1_RowCommand” AutoGenerateColumns=“false” AllowPaging=“true”
  6.                         CssClass=“table table-hover table-striped”>
  7.                         <Columns>
  8.                             <asp:BoundField DataField=“id” HeaderText=“ID”/>
  9.                             <asp:BoundField DataField=“FirstName” HeaderText=“FirstName”/>
  10.                                   <asp:BoundField DataField=“MiddleName” HeaderText=“MiddleName”/>
  11.                             <asp:BoundField DataField=“LastName” HeaderText=“LastName”/>
  12.                             <asp:BoundField DataField=“Address” HeaderText=“Address”/>
  13.                             <asp:BoundField DataField=“Landmark” HeaderText=“Landmark”/>
  14.                             <asp:BoundField DataField=“EmailID” HeaderText=“Email”/>
  15.                              <asp:BoundField DataField=“Country” HeaderText=“Country”/>
  16.                              <asp:BoundField DataField=“State” HeaderText=“State”/>
  17.                              <asp:BoundField DataField=“City” HeaderText=“City”/>
  18.                              <asp:BoundField DataField=“MobileNumber” HeaderText=“MobileNo”/>
  19.                          <asp:ButtonField CommandName=“editRecord”    ControlStyle-CssClass=“btn btn-info”
  20.                                 ButtonType=“Button” Text=“Edit” HeaderText=“Edit Record” >
  21.                                 <ControlStyle CssClass=“btn btn-primary” ></ControlStyle>
  22.                             </asp:ButtonField>
  23.                             <asp:ButtonField CommandName=“deleteRecord” ControlStyle-CssClass=“btn btn-info”
  24.                                 ButtonType=“Button” Text=“Delete” HeaderText=“Delete Record”>
  25.                                 <ControlStyle CssClass=“btn btn-danger”></ControlStyle>
  26.                             </asp:ButtonField>
  27.                         </Columns>
  28.                     </asp:GridView>
  29.                     <asp:Button ID=“btnAdd” runat=“server” Text=“Add New Record” CssClass=“btn btn-info” OnClick=“btnAdd_Click” />
  30.                 </ContentTemplate>
  31.                 <Triggers>
  32.                 </Triggers>
  33.             </asp:UpdatePanel>

Here, in this code, we are selecting records from our database along with buttons for edit and delete; and at the bottom, we are adding a button for adding a new record.

After setting up the GUI for “Select”, let’s create a simple method for “Select” using LINQ to SQL.

  1. private void BindEmployee()
  2.        {
  3.            SampleDataContext dbcontext = new SampleDataContext();
  4.            GridView1.DataSource = from reg in dbcontext.registrations
  5.                                   select reg;
  6.            GridView1.DataBind();
  7.        }

Create a method as BindEmployee(), create an instance of your Sampledatacontext class, and bind the Grid View with a LINQ query.

So, it’s a simple straight forward code. Now, let’s run the application and check the output.

Output for Select


Insert Code

Now, let’s setup the GUI part for insert.

  1. <!– Add Record Modal Starts here–>
  2.             
    “addModal” class=“modal hide fade” tabindex=“-1” role=“dialog” aria-labelledby=“addModalLabel” aria-hidden=“true”>
  3.                 
    class=“modal-header”>
  4.                     “button” class=“close” data-dismiss=“modal” aria-hidden=“true”
  5.                     

    “addModalLabel”>Add New Record

  6.                 
  •                 <asp:UpdatePanel ID=“upAdd” runat=“server”>
  •                     <ContentTemplate>
  •                         
    class=“modal-body”>
  •                             
    class=“table table-bordered table-hover”>
  •                                   
  •                                     
  •                                     
  •                                 
  •                                   
  •                                     
  •                                     
  •                                 
  •                                 
  •                                     
  •                                     
  •                                 
  •                                 
  •                                     
  •                                     
  •                                 
  •                                 
  •                                     
  •                                     
  •                                 
  •                                      
  •                                     
  •                                     
  •                                 
  •                                      
  •                                     
  •                                     
  •                                 
  •                                      
  •                                     
  •                                     
  •                                 
  •                                      
  •                                     
  •                                     
  •                                 
  •                                      
  •                                     
  •                                     
  •                                 
  •                                      
  •                                     
  •                                     
  •                                 
  •                             
  • ID : 
  •                                         “txtIdAdd” runat=“server”>
  • FirstName : 
  •                                         “txtFirstName” runat=“server”>
  • MiddleName :
  •                                         “txtMiddleName” runat=“server”>
  • LastName:
  •                                         “txtLastName” runat=“server”>
  • Address:
  •                                         “txtAddress” runat=“server”>
  • Landmark:
  •                                         “txtLandmark” runat=“server”>
  • EmailID:
  •                                         “txtEmailID” runat=“server”>
  • Country:
  •                                         “txtCountry” runat=“server”>
  • State:
  •                                         “txtState” runat=“server”>
  • City:
  •                                         “txtCity” runat=“server”>
  • Mobilenumber:
  •                                         “txtMobileNumber” runat=“server”>
  •                         
  •                         
    class=“modal-footer”>
  •                             “btnAddRecord” runat=“server” Text=“Add” CssClass=“btn btn-primary” OnClick=“btnAddRecord_Click” />
  •                             class=“btn btn-info” data-dismiss=“modal” aria-hidden=“true”>Close
  •