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:
- Create a new object that includes the column data to be submitted.
- Add the new object to the LINQ to SQL Table collection associated with the target table in the database.
- 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:
Step 1: Design a Windows Forms form as shown in the following figure.
Step 2: On the "Click" event of the "Insert Data" button proide the following code.
Step 3: Press F5 to run project. Fill in the textboxes with proper input.
Step 4: Click on the "Insert Data" Button, you will see a message box stating the data was inserted successfully.
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.
Step 6: Output