daily pastebin goal
39%
SHARE
TWEET

Untitled

a guest Sep 14th, 2018 44 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Creating and deleting related data with Entity Framework in ASP.NET MVC
  2. public ActionResult Edit(int id)
  3.     {
  4.         Instructor instructor = db.Instructors
  5.             .Include(i => i.OfficeAssignment)
  6.             .Include(i => i.Courses)
  7.             .Where(i => i.InstructorID == id)
  8.             .Single();
  9.         PopulateAssignedCourseData(instructor);
  10.         return View(instructor);
  11.     }
  12.  
  13. public ActionResult Edit(int id, FormCollection formCollection, string[] selectedCourses)
  14. {
  15.     var instructorToUpdate = db.Instructors
  16.         .Include(i => i.OfficeAssignment)
  17.         .Include(i => i.Courses)
  18.         .Where(i => i.InstructorID == id)
  19.         .Single();
  20.     if (TryUpdateModel(instructorToUpdate, "", null, new string[] { "Courses" }))
  21.     {
  22.         try
  23.         {
  24.             if (String.IsNullOrWhiteSpace(instructorToUpdate.OfficeAssignment.Location))
  25.             {
  26.                 instructorToUpdate.OfficeAssignment = null;
  27.             }
  28.  
  29.             UpdateInstructorCourses(selectedCourses, instructorToUpdate);
  30.  
  31.             db.Entry(instructorToUpdate).State = EntityState.Modified;
  32.             db.SaveChanges();
  33.  
  34.             return RedirectToAction("Index");
  35.         }
  36.         catch (DataException)
  37.         {
  38.             //Log the error (add a variable name after DataException)
  39.             ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
  40.        }
  41.     }
  42.     PopulateAssignedCourseData(instructorToUpdate);
  43.     return View(instructorToUpdate);
  44. }
  45.    
  46. public ViewResult CreateInstructor()
  47.         {
  48.             return View();
  49.         }
  50.    
  51. [HttpPost]
  52.         public ActionResult CreateInstructor(Instructor instructor)
  53.         {
  54. db.Instructors.Add(instructor);
  55. db.Instructors.SaveChanges();
  56.  return View(); //There will be some other logic here typically such as redirecting on a successful creation or showing specific validation issues with the object .
  57.  
  58. }
  59.    
  60. public ActionResult DeleteInstructor(int instructorId)
  61.         {
  62. var instructor = new Instructor {Id = instructorId};
  63. db.Instructors.Attach(instructor);
  64. db.Instructors.Remove(instructor);
  65. db.Instructors.SaveChanges();
  66.             return View();
  67.         }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top