public async Task <Result <DishView> > UpdateAsync(DishToUpdate dish, CancellationToken cancellationToken = default)
        {
            DishDB dishToUpdate = await _context.Dishes.IgnoreQueryFilters().Include(c => c.DishTags).ThenInclude(sc => sc.Tag).AsNoTracking().FirstOrDefaultAsync(_ => _.Id == dish.Id);

            if (dishToUpdate is null)
            {
                return(Result <DishView> .Quite <DishView>(ExceptionConstants.DISH_WAS_NOT_FOUND));
            }
            var dishTagList = await _context.DishTags.Where(_ => _.DishId == dish.Id).AsNoTracking().ToListAsync(cancellationToken);

            _context.DishTags.RemoveRange(dishTagList);
            dishToUpdate.DishTags.Clear();
            await _context.SaveChangesAsync(cancellationToken);

            try
            {
                dishToUpdate          = _mapper.Map <DishDB>(dish);
                dishToUpdate.Modified = DateTime.Now;

                _context.Entry(dishToUpdate).Property(c => c.Name).IsModified        = true;
                _context.Entry(dishToUpdate).Property(c => c.Composition).IsModified = true;
                _context.Entry(dishToUpdate).Property(c => c.Description).IsModified = true;
                _context.Entry(dishToUpdate).Property(c => c.Price).IsModified       = true;
                _context.Entry(dishToUpdate).Property(c => c.Weight).IsModified      = true;
                _context.Entry(dishToUpdate).Property(c => c.Sale).IsModified        = true;
                _context.Entry(dishToUpdate).Property(c => c.Modified).IsModified    = true;

                await UpdateTagLinks(dish.TagNames, dishToUpdate);

                await _context.SaveChangesAsync(cancellationToken);

                DishDB dishAfterAdding = await _context.Dishes.Where(_ => _.Id == dishToUpdate.Id).Include(c => c.DishTags).ThenInclude(sc => sc.Tag).Select(_ => _).AsNoTracking().FirstOrDefaultAsync(cancellationToken);

                DishView view = _mapper.Map <DishView>(dishAfterAdding);
                view.TagList = CollectTagList(dishAfterAdding.DishTags, cancellationToken).Result;
                return(Result <DishView> .Ok(_mapper.Map <DishView>(view)));
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return(Result <DishView> .Fail <DishView>(ExceptionConstants.CANNOT_UPDATE_MODEL + ex.Message));
            }
            catch (DbUpdateException ex)
            {
                return(Result <DishView> .Fail <DishView>(ExceptionConstants.CANNOT_UPDATE_MODEL + ex.Message));
            }
        }
Exemplo n.º 2
0
        public async Task <IActionResult> Update([FromBody, CustomizeValidator] DishToUpdate dish, CancellationToken cancellationToken = default)
        {
            if (dish is null || !ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            try
            {
                var result = await _dishService.UpdateAsync(dish, cancellationToken);

                return(result.IsError ? throw new InvalidOperationException(result.Message)
                     : result.IsSuccess ? (IActionResult)Ok(result.Data)
                     : StatusCode(StatusCodes.Status206PartialContent, result.Message.CollectProblemDetailsPartialContent(HttpContext)));
            }
            catch (InvalidOperationException ex)
            {
                Log.Error(ex, ex.Message);
                return(StatusCode(StatusCodes.Status500InternalServerError, new CustumResult()
                {
                    Status = StatusCodes.Status500InternalServerError, Message = ex.Message
                }));
            }
        }
        public async void Dishes_UpdateAsync_PositiveAndNegative_Test()
        {
            var options = new DbContextOptionsBuilder <DreamFoodDeliveryContext>()
                          .UseInMemoryDatabase(databaseName: "Dishes_UpdateAsync_PositiveAndNegative_Test")
                          .Options;

            using (var context = new DreamFoodDeliveryContext(options))
            {
                context.AddRange(_dishes);
                await context.SaveChangesAsync();
            }

            using (var context = new DreamFoodDeliveryContext(options))
            {
                var dish = await context.Dishes.AsNoTracking().FirstOrDefaultAsync();

                var tagService = new TagService(_mapper, context);
                var service    = new DishService(_mapper, context, tagService);

                TagToAdd[] tags = new TagToAdd[] {
                    new TagToAdd
                    {
                        TagName = "New"
                    }
                };

                DishToUpdate updateDish = new DishToUpdate()
                {
                    Id          = dish.Id,
                    Name        = "Name",
                    Composition = "Composition",
                    Description = "Description",
                    Weight      = "Weight",
                    TagNames    = new HashSet <TagToAdd>(tags)
                };

                DishToUpdate failDish = new DishToUpdate()
                {
                    Id          = Guid.NewGuid(),
                    Name        = "Name",
                    Composition = "Composition",
                    Description = "Description",
                    Weight      = "Weight",
                    TagNames    = new HashSet <TagToAdd>(tags)
                };

                var resultPositive = await service.UpdateAsync(updateDish);

                var resultNegative = await service.UpdateAsync(failDish);

                resultPositive.IsSuccess.Should().BeTrue();
                resultPositive.Data.Name.Should().BeEquivalentTo(updateDish.Name);
                resultPositive.Data.Composition.Should().BeEquivalentTo(updateDish.Composition);
                resultPositive.Data.Description.Should().BeEquivalentTo(updateDish.Description);
                resultPositive.Data.Weight.Should().BeEquivalentTo(updateDish.Weight);
                resultPositive.Data.Name.Should().NotBeEquivalentTo(dish.Name);
                resultPositive.Data.Composition.Should().NotBeEquivalentTo(dish.Composition);
                resultPositive.Data.Description.Should().NotBeEquivalentTo(dish.Description);
                resultPositive.Data.Weight.Should().NotBeEquivalentTo(dish.Weight);

                resultNegative.IsSuccess.Should().BeFalse();
            }
        }