Tuesday, 20 September 2011

Updating the database without querying it using LINQ and C#

One can update the Database using LINQ i.e. By querying first and then go for update.

However, one can go for update directly rather then querying it and then go for update.

HOW to DO it

For ex: In my case I want to update the QuestionTable  of my database(say Quizzana)  on the the update button click event.

Follow the Steps below--------->

Step-1: 
Create a DataBase context as ( dbConnectionDataContext db = new dbConnectionDataContext( );)

Step-2:
 Now create an object of the type which you want to update, here mine is the question table so I had created a Question object and kept the Address in the var variable named  ' q ' but you can keep in a same class variable.

Step-3:
Now point the field on which basis you want to make update, here I am using Qno .

Step-4:
Then attach the Object created to the corresponding table of the DataContext and then only go for the updates otherwise it throw the exception.

Step-5:
Now refresh the DataContext as--- db.Refresh(System.Data.Linq.RefreshMode.KeepChanges,q); where Refresh is the Method that takes the RefreshMode and the object of the Object to update it.

Step-6:
Now you can call the SubmitChanges( ) to Update the Table of the Database using the data context.

The Code is here Below:-

 public void btnUpdate_Click(Object sender, eventargs e)
{

           dbConnectionDataContext db = new dbConnectionDataContext();
             var q = new Question();
              q.Qno = qno;
               db.Questions.Attach(q);
               q.Qns = tbQns.Text.Trim(); ;
                try
             {
                 db.Refresh(System.Data.Linq.RefreshMode.KeepChanges,q);
                 db.SubmitChanges();
                 MessageBox.Show(qno+" no. upated successfully");
                 this.Close();

             }
              catch (Exception ex) { MessageBox.Show(ex.ToString()); }
        }

No comments:

Post a Comment