protected void SaveButton_Click(object sender, EventArgs e) { // Use EF to connect to the server using (DefaultConn db = new DefaultConn()) { // use the Student model to create a new student object and // save a new record Student newStudent = new Student(); int StudentID = 0; if (Request.QueryString.Count > 0) // our URL has a StudentID in it { // 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 form 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 database if (StudentID == 0) { db.Students.Add(newStudent); } // save our changes - also updates and inserts db.SaveChanges(); // Redirect back to the updated students page Response.Redirect("~/Students.aspx"); } }
/** * <summary> * This method is used to detelte student records from the database using ef * </summary> * * @method StudentsGridView_RowDeleting * @param {object} sender * @param {GridViewDeleteEventArgs} e * @return {void} */ protected void StudentsGridView_RowDeleting(object sender, GridViewDeleteEventArgs e) { // store which row was selected for deletion int selectedRow = e.RowIndex; // get the selected StudentID using the grid's Datakey collection int StudentID = Convert.ToInt32(StudentsGridView.DataKeys[selectedRow].Values["StudentID"]); // use EF to find the selected student from DB and Remove it using (DefaultConn db = new DefaultConn()) { Student deletedStudent = (from studentRecords in db.Students where studentRecords.StudentID == StudentID select studentRecords).FirstOrDefault(); // remove the student record from the database db.Students.Remove(deletedStudent); // save changes to the db db.SaveChanges(); // refresh the grid this.GetStudents(); } }