Inserting 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.

 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 provide the following code.

Insert Data

Step 3. Press F5 to run the 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.

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.

Server Explorer

Step 6. Output

SQL table


Similar Articles