Пример #1
0
        public ActionResult Create([FromBody] KnuthMorrisPrattUpdateDto knuthMorrisPrattUpdateDto)
        {
            var knuthMorrisPrattInput = _mapper.Map <KnuthMorrisPrattInput>(knuthMorrisPrattUpdateDto);

            //Check that the user is not trying to create an input set with a name that already exists for the user.
            var inputSetWithNameExists = (from input in _dbContext.KnuthMorrisPrattInputs
                                          join owner in _dbContext.KnuthMorrisPrattInputOwners on input.KnuthMorrisPrattInputId equals owner.KnuthMorrisPrattInputId into inputs
                                          from i in inputs
                                          where i.AspNetUserId == _userManager.GetUserId(User) && input.Name == knuthMorrisPrattInput.Name
                                          select i).Any();

            if (inputSetWithNameExists)
            {
                return(StatusCode(405)); //Wrong method for updating an existing input set - use PUT.
            }

            //Check that the user does not already have 10 input sets saved.
            var kmpInputCount = _dbContext.KnuthMorrisPrattInputOwners.Where(o => o.AspNetUserId == _userManager.GetUserId(User)).Count();

            if (kmpInputCount >= 10)
            {
                return(StatusCode(403));
            }

            //Try to add the input set.
            var transaction = _dbContext.Database.BeginTransaction();

            try
            {
                _dbContext.KnuthMorrisPrattInputs.Add(knuthMorrisPrattInput);
                _dbContext.SaveChanges();

                _dbContext.KnuthMorrisPrattInputOwners.Add(new KnuthMorrisPrattInputOwner()
                {
                    AspNetUserId            = _userManager.GetUserId(User),
                    KnuthMorrisPrattInputId = knuthMorrisPrattInput.KnuthMorrisPrattInputId
                });
                _dbContext.SaveChanges();

                transaction.Commit();
            }
            catch
            {
                return(StatusCode(500));
            }

            var knuthMorrisPrattReadDto = _mapper.Map <KnuthMorrisPrattReadDto>(knuthMorrisPrattInput);

            knuthMorrisPrattReadDto.IsOwnedByUser = true;

            return(CreatedAtAction(nameof(GetById), knuthMorrisPrattReadDto));
        }
Пример #2
0
        public ActionResult Update(int id, [FromBody] KnuthMorrisPrattUpdateDto knuthMorrisPrattUpdateDto)
        {
            if (!IsInputSetOwnedByUser(id))
            {
                return(Forbid());
            }

            var existingKmpInput = _dbContext.KnuthMorrisPrattInputs.First(k => k.KnuthMorrisPrattInputId == id);

            _dbContext.Entry(existingKmpInput).CurrentValues.SetValues(knuthMorrisPrattUpdateDto);
            _dbContext.SaveChanges();

            return(Ok());
        }