public TimesheetController()
 {
     _timesheetContext = new TimesheetContext();
 }
        public JsonResult Save(TimesheetViewModel timeSheetViewModel)
        {
            if (!ModelState.IsValid)
            {
                throw new ModelStateException(ModelState);
            }

            Timesheet timeSheet = ViewModels.Helpers.CreateTimesheetFromTimesheetViewModel(timeSheetViewModel);

            _timesheetContext.Timesheets.Attach(timeSheet);

            if (timeSheet.ObjectState == ObjectState.Deleted)
            {
                foreach (TimesheetItemViewModel timeSheetItemViewModel in timeSheetViewModel.TimesheetItems)
                {
                    TimesheetItem timeSheetItem = _timesheetContext.TimesheetItems.Find(timeSheetItemViewModel.TimesheetItemId);
                    if (timeSheetItem != null)
                        timeSheetItem.ObjectState = ObjectState.Deleted;
                }
            }
            else
            {
                foreach (int timeSheetItemId in timeSheetViewModel.TimesheetItemsToDelete)
                {
                    TimesheetItem timeSheetItem = _timesheetContext.TimesheetItems.Find(timeSheetItemId);
                    if (timeSheetItem != null)
                        timeSheetItem.ObjectState = ObjectState.Deleted;
                }
            }

            _timesheetContext.ApplyStateChanges();
            string messageToClient = string.Empty;

            try
            {
                _timesheetContext.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                messageToClient = "Someone else have modified this timesheet since you retrieved it.  Your changes have not been applied.  What you see now are the current values in the database.";
            }
            catch (Exception ex)
            {
                throw new ModelStateException(ex);
            }

            if (timeSheet.ObjectState == ObjectState.Deleted)
                return Json(new { newLocation = "/Timesheet/Index/" });

            if (messageToClient.Trim().Length == 0)
                //messageToClient = ViewModels.Helpers.GetMessageToClient(timeSheetViewModel.ObjectState, timeSheet.EmployeeName);

                timeSheetViewModel.TimesheetId = timeSheet.TimesheetId;
            _timesheetContext.Dispose();
            _timesheetContext = new TimesheetContext();
            timeSheet = _timesheetContext.Timesheets.Find(timeSheetViewModel.TimesheetId);

            timeSheetViewModel = ViewModels.Helpers.CreateTimesheetViewModelFromTimesheet(timeSheet);
            timeSheetViewModel.MessageToClient = messageToClient;

            return Json(new { timeSheetViewModel = timeSheetViewModel });
        }