示例#1
0
        public async Task <IActionResult> Post([FromBody] Goal goal)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var exiting = _context.Goals.FirstOrDefault(x => x.Id == goal.Id);

            if (exiting == null)
            {
                if (!HelperExtensions.CheckGoalCreateValues(goal))
                {
                    return(BadRequest(new MissingFieldException("CreateUserId value required")));
                }

                //ADD GOAL
                HelperExtensions.ClearNullableInts(goal);
                _context.Goals.Add(goal);
                await _context.SaveChangesAsync();

                return(Created(goal));
            }
            else
            {
                if (!HelperExtensions.CheckGoalUpdateValues(goal))
                {
                    return(BadRequest(new MissingFieldException("LastUpdateUserId value required")));
                }

                //UPDATE
                goal.CreateDate = exiting.CreateDate;
                goal.CreateUser = exiting.CreateUser;
                _context.Entry(exiting).CurrentValues.SetValues(goal);
                await _context.SaveChangesAsync();

                //ADD/UPDATE QUESTIONS
                var qc = new QuestionsController(_context);
                foreach (var question in goal.Questions)
                {
                    question.Goal = exiting;
                    await qc.Post(question);
                }

                return(Updated(exiting));
            }
        }