/// <summary> /// Action method to change the room /// </summary> /// <param name="userInput">the form filled by the user</param> /// <returns></returns> public ActionResult ChangeRoomAllotment(ChangeRoomViewModel userInput) { // get the student, current allotment and room string bid = (string)TempData.Peek("bid"); StudentHelper helper = new StudentHelper(); return(Content(helper.PerformRoomChange(userInput, bid))); }
/// <summary> /// Method to change the allotment for a student /// </summary> /// <param name="userInput">the form that the user has filled</param> /// <param name="bid">the bid of the student</param> /// <returns>the result to be displayed to the user</returns> public string PerformRoomChange(ChangeRoomViewModel userInput, string bid) { TransactionHelper helper = new TransactionHelper(); Student student = GetStudent(bid); Allotment allotment = student.Allotments.OrderByDescending(x => x.year).First(); Room currentRoom = db.Rooms.Where(x => x.hostelBlockNumber == allotment.hostelBlock && x.roomNumber == allotment.roomNum).First(); userInput.year = helper.GetAcademicYear(DateTime.Now); // if the user did not make any changes if (allotment.hostelBlock == userInput.hostelBlock && allotment.roomNum == userInput.roomNumber) { return("No change detected!"); } if (student.HostelTransactions.Where(x => x.year == userInput.year).ToList().Count > 0) { return("Hostel Transactions for the year have been performed, can not change room"); } // initiate a transaction using (var transaction = db.Database.BeginTransaction()) { try { // reduce the occupancy in the current room currentRoom.currentOccupancy = currentRoom.currentOccupancy - 1; db.Rooms.Attach(currentRoom); db.Entry(currentRoom).State = EntityState.Modified; db.SaveChanges(); // add the date of leave allotment.dateOfLeave = DateTime.Now; db.Allotments.Attach(allotment); db.Entry(allotment).State = EntityState.Modified; db.SaveChanges(); // add the new allotment db.Allotments.Add(new Allotment() { bid = student.bid, dateOfJoin = DateTime.Now, year = userInput.year, hostelBlock = userInput.hostelBlock, roomNum = userInput.roomNumber, }); db.SaveChanges(); // change the current occupancy in the new room Room newRoom = db.Rooms.Where(x => x.hostelBlockNumber == userInput.hostelBlock && x.roomNumber == userInput.roomNumber).First(); newRoom.currentOccupancy = newRoom.currentOccupancy + 1; db.Rooms.Attach(newRoom); db.Entry(newRoom).State = EntityState.Modified; db.SaveChanges(); // commit the transaction transaction.Commit(); } catch (Exception) { transaction.Rollback(); return("An error occured! Please try again later!"); } } return("Success!"); }