protected void SaveButton_Click(object sender, EventArgs e) { //use EF to connect to server using (ContosoConnection db = new ContosoConnection()) { //use Stundent model to create new student object and save new record Student newStudent = new Student(); int StudentID = 0; //ou url has a student id if (Request.QueryString.Count > 0) { //get the id from the url StudentID = Convert.ToInt32(Request.QueryString["StudentID"]); //get the current student from EF DB newStudent = (from student in db.Students where student.StudentID == StudentID select student).FirstOrDefault(); } //add data to the new student record newStudent.LastName = LastNameTextBox.Text; newStudent.FirstMidName = FirstNameTextBox.Text; newStudent.EnrollmentDate = Convert.ToDateTime(EnrollmentDateTextBox.Text); //use LINQ to ADO.NET to add/insert new student into the databasee if (StudentID == 0) { db.Students.Add(newStudent); } //save our changes and updates and inserts db.SaveChanges(); //redirect to updated students page Response.Redirect("~/Contoso/Students.aspx"); } }
/// <summary> /// This event handler deletes students from the database using Entity Framework /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void StudentsGridView_RowDeleting(object sender, GridViewDeleteEventArgs e) { //show whic row was clicked int selectedRow = e.RowIndex; //get the selected StudentID uing the grids data key collections int StudentID = Convert.ToInt32(StudentsGridView.DataKeys[selectedRow].Values["StudentID"]); //use EF to find the selected student in the DB and remove it using (ContosoConnection db = new ContosoConnection()) { //create object of the student class and tore the query string inside it Student deletedStudent = (from studentRecords in db.Students where studentRecords.StudentID == StudentID select studentRecords).FirstOrDefault(); //remove selected student db.Students.Remove(deletedStudent); // save my changes back to the database db.SaveChanges(); //refresh grid this.GetStudents(); } }