Thursday, 4 June 2015

Linq Query


The SELECT Operation
private void GetCourses()
{
      
//create DataContext object      OperationDataContext OdContext = new OperationDataContext();
      var courseTable = from course in OdContext.GetTable<COURSE>() select course;
      
//grdCourse is gridview id      grdCourse.DataSource = courseTable;
      grdCourse.DataBind();
}


The INSERT Operation
private void AddNewCourse()
{
      
//Data maping object to our database      OperationDataContext OdContext = new OperationDataContext();
      COURSE objCourse = new COURSE();
      objCourse.course_name = "B.Tech";
      objCourse.course_desc = "Bachelor Of Technology";
      objCourse.modified_date = DateTime.Now;
      
//Adds an entity in a pending insert state to this System.Data.Linq.Table<TEntity>and parameter is the entity which to be added      OdContext.COURSEs.InsertOnSubmit(objCourse);
      
// executes the appropriate commands to implement the changes to the database      OdContext.SubmitChanges();
}

The Update Operation
private void UpdateCourse()
{
      OperationDataContext OdContext = new OperationDataContext();
      
//Get Single course which need to update      COURSE objCourse = OdContext.COURSEs.Single(course => course.course_name == "B.Tech");
      
//Field which will be update      objCourse.course_desc = "Bachelor of Technology";
      
// executes the appropriate commands to implement the changes to the database      OdContext.SubmitChanges();
 }


The DELETE Operation
private void DeleteCourse()
{
      OperationDataContext OdContext = new OperationDataContext();
      
//Get Single course which need to Delete      COURSE objCourse = OdContext.COURSEs.Single(course => course.course_name == "B.Tech");
      
//Puts an entity from this table into a pending delete state and parameter is the entity which to be deleted.      OdContext.COURSEs.DeleteOnSubmit(objCourse);
      
// executes the appropriate commands to implement the changes to the database      OdContext.SubmitChanges();
}


Conculsion
To perform select, insert, update and delete operations we create a table and create a data context class; in other words a dbml file. In this file designer view we drag and drop the COURSE table from the Server Explorer. This data context class is an Object and table mapping and we perform the operation on the object and database updated according to the action using the submitChanges() method.

No comments:

Post a Comment