title: Async web api method to store files on disk but additional save each on to database
body: <p>I noticed that due to the nature of the async upload widget I am using my web api method gets called on multiple threads, one for each file being uploaded. I am trying to combine this with saving all of the files to the database. I am not sure how it is working right now exactly, but at the very end of everything all of the photo records are saved to the database. The problem is I am not able to set the correct sort order for each one of them they all have a SortOrder of 1 except for the last one.</p>
  
  <p>Here is my web api method which is acting very odd:</p>
  
  <pre><code>[HttpPost("{id}/photos")]
  public IActionResult SavePhotos(int id, IEnumerable&lt;IFormFile&gt; photos)
  {
      if (photos != null)
      {
          var product = _unitOfWork.Products.GetProductWithPhotos(id);
  
          foreach (var photo in photos)
          {
              if (photo.Length &gt; 0)
              {
                  var productPhotosPath = Path.Combine(_environment.WebRootPath, _settings.ProductUploadPath, product.Name);
  
                  string randomFileName = Path.GetRandomFileName();
                  randomFileName = Path.ChangeExtension(randomFileName, Path.GetExtension(photo.FileName));
                  using (var fileStream = new FileStream(Path.Combine(productPhotosPath, randomFileName), FileMode.Create))
                  {
                      photo.CopyTo(fileStream);
                  }
  
                  int maxSortOrder = product.Photos.Any() ? product.Photos.Max(p =&gt; p.SortOrder) : 0;
                  Photo photoToSave = new Photo()
                  {
                      ProductId = product.Id,
                      OriginalImageName = photo.FileName,
                      SavedImageName = randomFileName,
                      SortOrder = maxSortOrder + 1
                  };
  
                  _unitOfWork.Photos.Add(photoToSave);
              }
          }
  
          _unitOfWork.Complete();
      }
  
      return new EmptyResult();
  }
  </code></pre>