Thursday, May 26, 2011

Yet another simple way to associate One-To-One relation and to modify both tables.

There's a sample to associate One-To-One relation and to modify both tables in ASP.NET MVC3.
But there is some margin for more CoC. So I describe yet another simple way.

Associate One-To-One relation

  1. No descriptions in OnModelCreating
  2. Instructor class : same as the original
        public class Instructor
        {
            public int InstructorId { get; set; }
            ...
            public virtual OfficeAssignment OfficeAssignment { get; set; }
        }
  3. OfficeAssignment class : Use ForeignKey attribute instead of Key attribute
        public class OfficeAssignment
        {
            [ForeignKey("Instructor")]
            public int OfficeAssignmentId { get; set; }
            ...
            public virtual Instructor Instructor { get; set; }
        }

Modify both tables of One-To-One relation

There are 4 actions to fix from scaffolded ones. Usgin eager-loading makes actions for modify simple.
  • HTTP GET Create action : instantiate OfficeAssignment model
            //
            // GET: /Instructors/Create
            public ActionResult Create()
            {
                return View(new Instructor() { OfficeAssignment = new OfficeAssignment() });
            }
  • HTTP GET Edit action : eager-load table of OfficeAssignment model
            //
            // GET: /Instructors/Edit/5
            public ActionResult Edit(int id)
            {
                Instructor instructor = db.Instructors.Include(i => i.OfficeAssignment).Where(i => i.InstructorId == id).Single();
                return View(instructor);
            }
  • HTTP POST Edit action : eager-load table of OfficeAssignment model and use TryUpdateModel utility method
            //
            // POST: /Instructors/Edit/5
            [HttpPost]
            public ActionResult Edit(Instructor instructor)
            {
                Instructor instructorToGo = db.Instructors.Include(i => i.OfficeAssignment).Where(i => i.InstructorId == instructor.InstructorId).Single();
                if (TryUpdateModel(instructorToGo))
                {
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
                else
                {
                    return View(instructorToGo);
                }
            }
  • HTTP POST Delete action : eager-load table of OfficeAssignment model
            //
            // POST: /Instructors/Delete/5
            [HttpPost, ActionName("Delete")]
            public ActionResult DeleteConfirmed(int id)
            {
                Instructor instructor = db.Instructors.Include(i => i.OfficeAssignment).Where(i => i.InstructorId == id).Single();
                db.Instructors.Remove(instructor);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

No comments:

Post a Comment