示例#1
0
        public ActionResult Save(WeekValuesFormViewModel viewModel)
        {
            if (!ModelState.IsValid)
            {
                return(View("WeekValuesForm", viewModel));
            }

            if (viewModel.WeekValues.Id == 0)
            {
                _context.WeekValues.Add(viewModel.WeekValues);
                try
                {
                    _context.SaveChanges();
                }
                catch (DbEntityValidationException e)
                {
                    Console.WriteLine(e);
                }

                var week = new Week();
                week = viewModel.Week;
                week.WeekValuesId = viewModel.WeekValues.Id;
                week.CalculatePattern(viewModel.WeekValues);
                week.CalculateProfit();

                _context.Weeks.Add(week);
            }
            else
            {
                // For the FK
                viewModel.Week.WeekValuesId = viewModel.WeekValues.Id;

                viewModel.Week.CalculatePattern(viewModel.WeekValues);
                viewModel.Week.CalculateProfit();

                var weekValuesInDB = _context.WeekValues.Single(w => w.Id == viewModel.WeekValues.Id);
                var weekInDB       = _context.Weeks.Single(w => w.Id == viewModel.Week.Id);

                weekValuesInDB.Map(viewModel.WeekValues);
                weekInDB.Map(viewModel.Week);
            }

            try
            {
                _context.SaveChanges();
            }
            catch (DbEntityValidationException e)
            {
                Console.WriteLine(e);
            }

            return(RedirectToAction("Index", "Weeks"));
        }