public async Task <IActionResult> CreateBike([FromForm] BikeMultiPartDTO model) { using (var transaction = _context.Database.BeginTransaction()) { try { if (model != null) { StoreImages storeImage = new StoreImages(); storeImage.Description = $"Bike '{model.Bike.Brand} - {model.Bike.Model}' image files"; _storeImgRepo.Add(storeImage); await _storeImgRepo.SaveChangesAsync(); if (model.Files.Any()) { // save bike images foreach (var file in model.Files) { if (file.Length > 0) { using (var ms = new MemoryStream()) { file.CopyTo(ms); var fileBytes = ms.ToArray(); _imgContentRepo.Add(new ImgContent { ImgContentMimeType = file.ContentType, StoreImgId = storeImage.StoreImgId, ImgCreateDt = DateTime.UtcNow, ImgContentName = file.FileName, Content = fileBytes, IsThumbnail = file.FileName.Equals(model.Bike.ThumbFileName) }); await _imgContentRepo.SaveChangesAsync(); } } } } Bike bike = _mapper.Map <BikeForCreation, Bike> (model.Bike); bike.ImgId = storeImage.StoreImgId; //create new bike _bikeRepository.CreateBike(bike); await _bikeRepository.SaveChangesAsync(); // add junction with colors _bikesColorsRepo.AddRange(model.Bike.Colors.Select(colorId => new BikesColors() { BikeId = bike.BikeId, ColorId = colorId }).ToList()); await _bikesColorsRepo.SaveChangesAsync(); // add junction with sizes _bikesSizesRepo.AddRange(model.Bike.Sizes.Select(sizeId => new BikesSizes() { BikeId = bike.BikeId, SizeId = sizeId }).ToList()); await _bikesSizesRepo.SaveChangesAsync(); transaction.Commit(); return(Ok()); } return(BadRequest()); } catch (Exception ex) { transaction.Rollback(); return(StatusCode(500, $"Internal server error: {ex.Message}")); } } }