CRUD Operations With LINQ to SQL in ASP.Net

Language-Integrated Query (LINQ)

In Language-Integrated Query (LINQ) to SQL, the data model of a relational database is mapped to an object model expressed in the programming language of the developer. When the application runs, LINQ to SQL translates into SQL the language-integrated queries in the object model and sends them to the database for execution. When the database returns the results, LINQ to SQL translates them back to objects that you can work with in your own programming language (as per the MSDN).

All LINQ query operations consist of the following three distinct actions:

  1. Obtain the data source.
  2. Create the query.
  3. Execute the query.

In this article LINQ is done against a SQL database. So this explains how to do an insert, an edit, an update and a delete of records with LINQ to SQL step-by-step.

Step 1: Database

Create a LINQUser table as in the following.

  1. create table LinqUser  
  2. (  
  3.    Id int identity(1,1) primary key,  
  4.    Name varchar(30),  
  5.    Email nvarchar(50),  
  6.    Image nvarchar(max)  
  7. )  
Step 2: Visual Studio

Go to Solution Explorer and LINQ to SQL classes as in the following.

Linq to Sql Classes
Figure 1: LINQ to SQL Classes

Click the add button and open as in the following dialog box and click the Yes button.

Add App
Figure 2: Add App_Code

And the LINQ class is created in the App_code folder in the project's Solution Explorer as in the following.

Add
Figure 3: Add .dbml

Now maintain your database connection with Visual Studio and add a table to the LinqClass.dbml surface area as in the following from the Server Explorer.

Add Table
Figure 4: Add Table

Add Web form
Figure 5: Add Web form

Step 3: UI design

Now I will write the design code inside the .aspx page. In this page add some TextBox controls, a Button control and a GridView Control. And add a GridView Action event for an edit, a cancel, a delete and paging event.

The following is the UI design code.
  1. <%@ Page Title="" Language="C#" MasterPageFile="~/Master/Master.master" AutoEventWireup="true" CodeFile="LinqCRUDdemo.aspx.cs" Inherits="UI_LinqCRUDdemo" %>  
  2.   
  3. <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">  
  4. </asp:Content>  
  5. <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">  
  6. <div style="background-color: #66FF99; border: thin groove #FF0000; height: 138px; width: 400px;">  
  7. <fieldset style="width: 340px"><legend>Linq To Classes Demo</legend>  
  8.    <asp:Table runat="server">  
  9.         <asp:TableRow><asp:TableCell>Name</asp:TableCell><asp:TableCell><asp:TextBox ID="txtName" runat="server"></asp:TextBox></asp:TableCell></asp:TableRow>  
  10.         <asp:TableRow><asp:TableCell>Email ID</asp:TableCell><asp:TableCell><asp:TextBox ID="txtEmail" runat="server"></asp:TextBox></asp:TableCell></asp:TableRow>  
  11.         <asp:TableRow><asp:TableCell>Upload Image</asp:TableCell><asp:TableCell><asp:FileUpload ID="FileUpload1" runat="server" /></asp:TableCell></asp:TableRow>  
  12.         <asp:TableRow><asp:TableCell></asp:TableCell><asp:TableCell><asp:Button ID="btnsave" runat="server" Text="Save" onclick="btnsave_Click" /> </asp:TableCell></asp:TableRow>  
  13.     </asp:Table>  
  14. </fieldset>  
  15. </div><br />  
  16.     <asp:GridView ID="GridUser" runat="server" AutoGenerateColumns="False" DataKeyNames="id"  
  17.         AllowPaging="True"  PageSize="3"   
  18.         OnRowCancelingEdit="GridUser_RowCancelingEdit"   
  19.         OnRowDeleting="GridUser_RowDeleting"   
  20.         OnRowEditing="GridUser_RowEditing"   
  21.         OnRowUpdating="GridUser_RowUpdating" OnPageIndexChanging="GridUser_PageIndexChanging" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2">  
  22.             <Columns>  
  23.                 <asp:TemplateField HeaderText="Name">  
  24.                     <EditItemTemplate>  
  25.                         <asp:TextBox ID="txtName" runat="server" Text='<%# Eval("Name") %>'></asp:TextBox>  
  26.                     </EditItemTemplate>  
  27.                     <ItemTemplate>  
  28.                         <asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>  
  29.                     </ItemTemplate>  
  30.                 </asp:TemplateField>  
  31.                 <asp:TemplateField HeaderText="Email ID">  
  32.                     <EditItemTemplate>  
  33.                         <asp:TextBox ID="txtEmail" runat="server" Text='<%# Eval("Email") %>'></asp:TextBox>  
  34.                     </EditItemTemplate>  
  35.                     <ItemTemplate>  
  36.                         <asp:Label ID="lblEmail" runat="server" Text='<%# Eval("Email") %>'></asp:Label>  
  37.                     </ItemTemplate>  
  38.                 </asp:TemplateField>  
  39.                   
  40.                 <asp:TemplateField HeaderText="Image">  
  41.                     <ItemTemplate>  
  42.                         <asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("Image") %>' Height="100px" Width="100px"/>  
  43.                     </ItemTemplate>  
  44.                 </asp:TemplateField>  
  45.   
  46.                 <asp:CommandField ShowEditButton="True" />  
  47.                 <asp:CommandField ShowDeleteButton="True" />  
  48.             </Columns>  
  49.             <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />  
  50.             <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />  
  51.             <PagerSettings PageButtonCount="8" />  
  52.             <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />  
  53.             <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />  
  54.             <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />  
  55.             <SortedAscendingCellStyle BackColor="#FFF1D4" />  
  56.             <SortedAscendingHeaderStyle BackColor="#B95C30" />  
  57.             <SortedDescendingCellStyle BackColor="#F1E5CE" />  
  58.             <SortedDescendingHeaderStyle BackColor="#93451F" />  
  59.         </asp:GridView>  
  60.      
  61. </asp:Content>  
Go to the GridView control's property and add a GridView Action Event as in the following.

Grid Action
Figure 6: Grid Action

And also maintain a Data key field in the GridView to an edit and a delete command.

Step 4: UI Code

First write code to insert the TextBox data into the database using LINQ to SQL Classes. Then the data is retrieved from the database and the record is edited and deleted with the LINQ to SQL classes as in the following code.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7.   
  8. public partial class UI_LinqCRUDdemo : System.Web.UI.Page  
  9. {  
  10.     LinqClassDataContext db = new LinqClassDataContext();  
  11.     protected void Page_Load(object sender, EventArgs e)  
  12.     {  
  13.         if (!IsPostBack)  
  14.         {  
  15.             Bindgrid();  
  16.         }  
  17.     }  
  18.     protected void btnsave_Click(object sender, EventArgs e)  
  19.     {  
  20.   
  21.         string image = Server.MapPath("~/Images/") + Guid.NewGuid() + FileUpload1.PostedFile.FileName;  
  22.         FileUpload1.PostedFile.SaveAs(image);  
  23.         string File = image.Substring(image.LastIndexOf("\\"));  
  24.         string[] split = File.Split('\\');  
  25.         string ImgPath = split[1];  
  26.         string imagepath = "~/Images/" + ImgPath;  
  27.        
  28.         LinqUser LU = new LinqUser();  
  29.   
  30.                 LU.Name = txtName.Text;  
  31.                 LU.Email = txtEmail.Text;  
  32.                 LU.Image = imagepath;  
  33.                 db.LinqUsers.InsertOnSubmit(LU);  
  34.                 db.SubmitChanges();  
  35.                 Clear();  
  36.         Bindgrid();  
  37.     }  
  38.     private void Clear()  
  39.     {  
  40.         txtName.Text = string.Empty;  
  41.         txtEmail.Text = string.Empty;  
  42.     }  
  43.     private void Bindgrid()  
  44.     {  
  45.         var bind = from c in db.LinqUsers select c;  
  46.         GridUser.DataSource = bind;  
  47.         GridUser.DataBind();  
  48.     }  
  49.     protected void GridUser_RowDeleting(object sender, GridViewDeleteEventArgs e)  
  50.     {  
  51.         
  52.             int ID = Convert.ToInt32(GridUser.DataKeys[e.RowIndex].Value);  
  53.             LinqUser LU = db.LinqUsers.First(x => x.Id == ID);  
  54.   
  55.             db.LinqUsers.DeleteOnSubmit(LU);  
  56.             db.SubmitChanges();  
  57.             Bindgrid();  
  58.     }  
  59.     protected void GridUser_RowEditing(object sender, GridViewEditEventArgs e)  
  60.     {  
  61.         GridUser.EditIndex = e.NewEditIndex;  
  62.         Bindgrid();  
  63.     }  
  64.     protected void GridUser_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)  
  65.     {  
  66.         GridUser.EditIndex = -1;  
  67.         Bindgrid();  
  68.     }  
  69.     protected void GridUser_RowUpdating(object sender, GridViewUpdateEventArgs e)  
  70.     {  
  71.             GridViewRow row = GridUser.Rows[e.RowIndex];  
  72.             TextBox txtName = (TextBox)row.FindControl("txtName");  
  73.             TextBox txtEmail = (TextBox)row.FindControl("txtEmail");  
  74.               
  75.             int ID = Convert.ToInt32(GridUser.DataKeys[e.RowIndex].Value);  
  76.              
  77.             LinqUser LU = db.LinqUsers.First(x => x.Id == ID);  
  78.           
  79.             LU.Name = txtName.Text;  
  80.             LU.Email = txtEmail.Text;  
  81.              
  82.             db.SubmitChanges();  
  83.             GridUser.EditIndex = -1;  
  84.             Bindgrid();  
  85.          
  86.     }  
  87.     protected void GridUser_PageIndexChanging(object sender, GridViewPageEventArgs e)  
  88.     {  
  89.         GridUser.PageIndex = e.NewPageIndex;  
  90.         Bindgrid();  
  91.     }  
  92. }  
Step 5: Run Code

Fill Record
Figure 7: Fill Record

Now fill in some records and save in the database.

Record Display in Grid using LINQ to SQL
Figure 8: Record Display in Grid using LINQ to SQL

Now create an update and delete record process using an Edit and a Delete button command as in the following.

Update and Delete record
Figure 9: Update and Delete record

Record Updated
Figure 10: Record Updated

I hope you understand how to use LINQ to SQL Classes to do SQL Table CRUD operations.

Good Day Sir.
Happy Coding.

 


Similar Articles