示例#1
0
        public async Task Update_NonExisting_AddsToDatabase()
        {
            var opt = new DbContextOptionsBuilder <ProductContext>()
                      .UseInMemoryDatabase(nameof(Update_NonExisting_AddsToDatabase))
                      .Options;
            var     request = new Product(12, "Coconut", 0.5f);
            Product createdProduct;

            await using (var ctx = new ProductContext(opt))
            {
                var service = new ProductsRepository(ctx);
                createdProduct = await service.Update(request);
            }

            await using (var ctx = new ProductContext(opt))
            {
                Assert.AreEqual(1, ctx.Products.Count());
                Assert.AreEqual(0.5f, ctx.Products.Single().Price);
                Assert.AreEqual(true, createdProduct.Created);
            }
        }
        public async Task <ProductDTO> Update(ProductDTO update)
        {
            try
            {
                var product = await Find(update.Id);

                product.Name  = update.Name;
                product.Price = update.Price;
                await _context.SaveChangesAsync();

                return(product.ToDomain());
            }
            catch (ProductNotFoundException)
            {
                return(await Create(new Product
                {
                    Id = update.Id,
                    Name = update.Name,
                    Price = update.Price
                }));
            }
        }