Inserting Data in the Database Using LINQ to SQL

In this article you will learn how to insert data in the database using LINQ to SQL.

Rows can be inserted into a database by adding objects to the associated LINQ to SQL Table "<TEntity>" collection and then submitting the changes to the database. LINQ to SQL translates your changes into the appropriate SQL INSERT commands.

The following steps assume that you have made a valid DataContext connection to the database.

Inserting a row

Use the following procedure to insert a row into the database:

  1. Create a new object that includes the column data to be submitted.
  2. Add the new object to the LINQ to SQL Table collection associated with the target table in the database.
  3. Submit the change to the database.

Example: In the following example we will insert data in the tblEmployee using LINQ. The structure of the tblEmployee table is as follows:

sql table structure

Step 1: Design a Windows Forms form as shown in the following figure.

window form interface

Step 2: On the "Click" event of the "Insert Data" button proide the following code.

Click Event to insert data

Step 3: Press F5 to run project. Fill in the textboxes with proper input.

windows form button

Step 4: Click on the "Insert Data" Button, you will see a message box stating the data was inserted successfully.

message box in windows application

Step 5: Open the table and check the data. In the Server Explorer right-click on the table and select "Show table data" as shown below.

chec data table in sql
Step 6: Output

sql table