public async Task Handle(ProductCreateCommand command, CancellationToken cancellationToken ) { await _context.AddAsync(new Product { Price = command.Price, Description = command.Description, Name = command.Name }, cancellationToken) .ConfigureAwait(false); await _context.SaveChangesAsync(cancellationToken) .ConfigureAwait(false); }
public async Task Handle(ProductInStockUpdateStockCommand command, CancellationToken cancellationToken) { _logger.LogInformation("--- ProductInStockUpdateStockCommand started"); var products = command.Items.Select(item => item.ProductId); var stocks = await _context.Stock .Where(x => products.Contains(x.ProductId)) .ToListAsync(cancellationToken); _logger.LogInformation("--- Retrieving products from database"); foreach (var item in command.Items) { var entry = stocks.SingleOrDefault(x => x.ProductId == item.ProductId); if (item.Action == ProductInStockAction.Subtract) { if (entry is null || item.Stock > entry.Stock) { _logger.LogError($"Product {entry.ProductId} - does not have enough stock"); throw new ArgumentException($"Product {entry.ProductId} - does not have enough stock"); } _logger.LogInformation($"--- Product {entry.ProductId} - stock subtracted - new stock {entry.Stock}"); entry.Stock -= item.Stock; } else { if (entry is null) { entry = new ProductInStock { ProductId = item.ProductId }; await _context.AddAsync(entry, cancellationToken); _logger.LogInformation($"--- New Stock created for {entry.ProductId} - because it has not a previous stock"); } entry.Stock += item.Stock; _logger.LogInformation($"--- Product {entry.ProductId} - stock increased - new stock {entry.Stock}"); } } await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); _logger.LogInformation("--- ProductInStockUpdateStockCommand ended"); }
public async Task <Result <Guid> > StoreCatalogAsync(CatalogVM catalog) { string errSource = "SotreCatalogAsync"; Genre genre = await _context.Genres.FindAsync(catalog.GenreID); if (genre is null) { return(new ErrorResult <Guid>( code: ErrorCode.NotFound, message: $"Could not find any Genre with Id {catalog.GenreID}", errorSource: errSource)); } Developer developer = await _context.Developers.FindAsync(catalog.CompanyID); if (developer is null) { return(new ErrorResult <Guid>( code: ErrorCode.NotFound, message: $"Could not find any Game developer company with Id {catalog.CompanyID}", errorSource: errSource)); } Guid catalogID = Guid.NewGuid(); Mapper mapper = new Mapper(new MapperConfiguration(cfg => { cfg.CreateMap <CatalogVM, Catalog>() .AfterMap((src, des) => { des.ID = catalogID; des.Company = developer; des.Genre = genre; }); })); await _context.AddAsync <Catalog>(mapper.Map <Catalog>(catalog)); await _context.SaveChangesAsync(); return(new Result <Guid>() { Data = catalogID }); }