lwschan
lwschan

Reputation: 431

Keep Getting "A second operation started on this context before a previous operation completed" when saving to the context a second time.

I keep getting the following error when I am executing my HttpPost form a second time.

InvalidOperationException: A second operation started on this context before a previous operation completed. 

Any instance members are not guaranteed to be thread safe.

My ApplicationDbContext is initialised in my controller as such:

public class AssetController : Controller
{
    private readonly ApplicationDbContext _context;

    public AssetController(
        ApplicationDbContext context,)
    {
        _context = context;
    }

And this is the function in the controller that handles the post and save:

[HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Add(IFormFile file, AddAssetViewModel model)
    {
        if (ModelState.IsValid)
        {
            var currentUser = await _userManager.GetUserAsync(HttpContext.User);

            var assetOwnership =
                _context.AssetOwnership.SingleOrDefault(o => o.AssetOwnershipId == model.OwnershipId);

            var origin = _context.Location.SingleOrDefault(l => l.LocationId == model.OriginId);

            var currentLocation = _context.Location.SingleOrDefault(l => l.LocationId == model.CurrentLocationId);

            var division = _context.Division.SingleOrDefault(d => d.DivisionId == model.DivisionId);

            var normalAsset = model.NormalAsset == 2;

            var uploadSavePath = Path.Combine(_hostingEnvironment.WebRootPath, "Uploads\\AssetPictures\\");

            var trackingNumber = GetTrackingNumber(model.OwnershipId, model.DivisionId);

            var asset = new Asset
            {
                TrackingNum = trackingNumber,
                Owner = currentUser,
                Ownership = assetOwnership,
                CurrentLocation = currentLocation,
                Origin = origin,
                ModelName = model.ModelName,
                SerialNum = model.SerialNum,
                Division = division,
                Desc = model.Desc,
                HwOpt = model.HwOpt,
                SwOpt = model.SwOpt,
                Availability = model.Availability,
                Remarks = model.Remarks,
                ReadyToSell = model.ReadyToSell,
                PurchaseDate = model.PurchaseDate,
                PurchasePo = model.PurchasePo,
                NormalAsset = normalAsset,
                MaterialNumber = model.MaterialNum,
                IsTagged = model.IsTagged,
                PurchasePrice = model.PurchasePrice,
                IsDamaged = model.IsDamaged,
                LastCalDate = model.LastCalDate,
                Firmware = model.Firmware,
                EstimatedNextCalDate = model.EstimatedNextCalDate,
                LicenceExpiry = model.LicenceExpiry
            };

            if (file != null)
            {
                var imageName = asset.TrackingNum + ".jpg";

                if (file.Length > 0)
                {
                    using (var fileStream =
                        new FileStream(Path.Combine(uploadSavePath, imageName), FileMode.Create))
                    {
                        await file.CopyToAsync(fileStream);
                    }
                    asset.AssetPicture = imageName;
                }
            }

            _context.Asset.Add(asset);

            await _context.SaveChangesAsync();

            return RedirectToAction("Index");
        }
        return View(model);
}

}

When I am only submitting the form for the first time, everything goes fine, item is saved into the database properly. However, when I try to add a second item, I get the error. Can anybody help me to fix this? Error output is saying it fails at

Project.Controllers.AssetController+<Add>d__14.MoveNext() in AssetController.cs
+
            await _context.SaveChangesAsync();

Upvotes: 10

Views: 22274

Answers (1)

lwschan
lwschan

Reputation: 431

I finally fixed it. I forgot to make one of my helper method with async calls async and those calls await. So that messed up the whole thing.

Upvotes: 15

Related Questions