protected void btnSave_Click(object sender, EventArgs e) { //use EF to connect to SQL server using (comp2007Entities db = new comp2007Entities()) { //use the student model to save the new record Course c = new Course(); Int32 CourseID = 0; //check the query string for an id so we can determine add / update if (Request.QueryString["CourseID"] != null) { //get the ID from the URL CourseID = Convert.ToInt32(Request.QueryString["CourseID"]); //get the current student from Entity Framework c = (from objS in db.Courses where objS.CourseID == CourseID select objS).FirstOrDefault(); } c.Title= txtTitle.Text; c.Credits = Convert.ToInt32(txtCredits.Text); c.DepartmentID = Convert.ToInt32(ddDepartment.SelectedValue); //call add only if we have no student ID if (CourseID == 0) db.Courses.Add(c); db.SaveChanges(); //redirect to the updated students page Response.Redirect("courses.aspx"); } }
protected void btnSave_Click(object sender, EventArgs e) { //connect using (DefaultConnection conn = new DefaultConnection()) { //instantiate a new student object in memory Course c = new Course(); //decide if updating or adding, then save if (!String.IsNullOrEmpty(Request.QueryString["CourseID"])) { Int32 CourseID = Convert.ToInt32(Request.QueryString["CourseID"]); c = (from crs in conn.Courses where crs.CourseID == CourseID select crs).FirstOrDefault(); } //fill the properties of our object from the form inputs c.Title = txtTitle.Text; c.Credits = Convert.ToInt32(txtCredits.Text); c.DepartmentID = Convert.ToInt32(ddlDepartment.SelectedValue); if (Request.QueryString.Count == 0) { conn.Courses.Add(c); } conn.SaveChanges(); //redirect to updated departments page Response.Redirect("Courses.aspx"); } }