Insert Update & Delete using Linq to sql classes

I have learnt last week Linq to sql and i amazed by its features.I would like to share my knowledge with you.To insert,update and delete you need to write lesser amount of code hence it saves development time. Following is the step you need to follow in order to insert,update and delete data of database using Linq to sql in Asp.Net.

  • Open Visual Studio 2008, Click File >Website and choose ASP.Net Website. Choose the language of your choice and name your website according to your need.
  • In solution explorer, right the project and select “Add New Item”. Select “LINQ to SQL classes” as shown in below figure. I have named it as DataClasses1. This will add an EmployeeInfo.dbml file inside “App_Code” folder. 
  •  In Visual Studio,   DataClasses1.dbml will have 2 panes. The left pane is for deigning the data objects and the right pane can be used for creating methods that operates on the data objects.The Visual Studio toolbar will contain a new toolbar for designing LINQ to SQL objects.
  •  Once we include the LINQ to SQL Class in the project, there will be 3 files added to the App_Code.
  • Open Server Explorer, Expand the database tables.Drag  UnitType  into LINQ to SQL designer and click Save. The Objects will be created automatically.  It will also generate the DataContext object for these objects for interacting with the underlying datasource i.e. it is with the help of this DataContext class we can interact with the database objects in our managed environment. In our case, it is EmployeeInfoDataContext.
     Following is the step to Add, update and delete using Linq to sql

Inserting using Linq to sql

DataClasses1DataContext dc = new DataClasses1DataContext();
 ItemType it = new ItemType()
                    ItemCode = txtItemCode.Text,
                    ItemDesc = txtDescp.Text

Updating using Linq to sql

DataClasses1DataContext dc = new DataClasses1DataContext();
                ItemType it = (from c in dc.ItemTypes
                               where c.ID == Convert.ToInt32(Request.QueryString["ITypeId"])
                               select c).Single();

                it.ItemCode = txtItemCode.Text;
                it.ItemDesc = txtDescp.Text;


Deleting using Linq to sql

 DataClasses1DataContext dc = new DataClasses1DataContext();
            ItemType it = (from c in dc.ItemTypes
                           where c.ID == itemId
                           select c).Single();        



Popular posts from this blog

Implement Logging in CSV file using Nlog in .net core MVC application- part 2

Implement Nlog in .Net core MVC application part 1

Angular User Session Timeout example step by step

Devexpress Datebox date formatting in angular 6 with example

Restore the lost focus of Auto post back controls in update Panel control