web-dev-qa-db-ja.com

もう一度コンテキストに保存するときに、「前の操作が完了する前に、このコンテキストで2番目の操作が開始されました」という取得を続けます。

HttpPostフォームを2回実行すると、次のエラーが発生し続けます。

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

Any instance members are not guaranteed to be thread safe.

私のApplicationDbContextは、次のようにコントローラーで初期化されます。

public class AssetController : Controller
{
    private readonly ApplicationDbContext _context;

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

そして、これは投稿と保存を処理するコントローラーの関数です。

[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);
}

}

初めてフォームを送信するだけで、すべてがうまくいき、アイテムはデータベースに正しく保存されます。ただし、2つ目のアイテムを追加しようとすると、エラーが発生します。誰かが私がこれを修正するのを手伝ってくれる?エラー出力はそれがで失敗すると言っています

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

やっと直しました。 async呼び出しasyncを使用してヘルパーメソッドの1つを作成するのを忘れたので、それらの呼び出しが待機します。だからそれはすべてを台無しにした。

8
Lewis