Pages

Saturday 29 September 2012

How to insert data into database using Linq?

Step-1: Create a table in your database. In my example I have a table(EmpDetails) which will keep the details(EmployeeID,EmployeeName and Address) of an employee.
Step-2: Add a new "LINQ to SQL Classes" to your Solution. To add this file Right Click on your website=> Click on "Add New Item" =>Choose "LINQ to SQL Classes" from the list. Rename the file as your wish(Extension should be .dbml). I renames it to "EmployeeClass.dbml".
Now, a new file will be added to your solution and two layout panels will open in your design surface.
Step-3: Drag your table from the Server Explorer in to the left layout.
Step-4: Add fields in your page as per your table columns. Though in my case I have three fields and from those three "EmployeeID" is Auto-generated. So I have to send two values(EmployeeName,Address). That's why I added two textboxes into my page and a button also.
Step-5: Add "using System.Linq;" namespace to your Page. Then,write the following lines in the Button's Click Event to send the values to database.
protected void btnSubmit_Click(object sender, EventArgs e)
    {
        using (EmployeeClassDataContext context = new EmployeeClassDataContext())
        {
            EmpDetail details = new EmpDetail();
            details.Address = txtAddress.Text;
            details.EmployeeName = txtEmpName.Text;
            context.EmpDetails.InsertOnSubmit(details);
            context.SubmitChanges();
        }
    }


Step-6: Then, run your page and insert values you want to send to your database.
After inserting the values, when you click on the submit button, the values will be inserted into database.
Output:




Regards,
Prajanuranjan....


No comments:

Post a Comment

Total Pageviews