c# - 第二次保存到上下文时继续获取 "A second operation started on this context before a previous operation completed"。

标签 c# .net asp.net-mvc entity-framework

当我第二次执行 HttpPost 表单时,我不断收到以下错误。

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

Any instance members are not guaranteed to be thread safe.

我的 ApplicationDbContext 在我的 Controller 中初始化如下:

public class AssetController : Controller
{
    private readonly ApplicationDbContext _context;

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

这是 Controller 中处理发布和保存的函数:

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

}

当我第一次提交表单时,一切正常,项目已正确保存到数据库中。但是,当我尝试添加第二个项目时,出现错误。 有人可以帮我解决这个问题吗? 错误输出说它失败了

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

最佳答案

我终于修好了。我忘记使用异步调用异步创建我的辅助方法之一,这些调用等待。所以这搞砸了整个事情。

关于c# - 第二次保存到上下文时继续获取 "A second operation started on this context before a previous operation completed"。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44237977/

相关文章:

asp.net-mvc - 如何编写允许在 ASP.NET MVC 中使用下划线的路由?

c# - 如何通过加入获得最大日期的记录?

c# - 适用于 .net 的 Foursquare SDK

c# - 为什么 .NET 中的排序集合没有匹配的接口(interface)?

c# - 在 RichTextBox 中对行进行排序的最佳方法是什么

.net - vb.net错误使用界面

c# - 更改值适用于预加载但不适用于 linq 和 ef 中的惰性加载

c# - 压缩现有 XPS 文档

c# - 如何确定所选节点是 TreeView 中的子节点还是父节点?

asp.net - 如何将 MVC 4 中的值四舍五入到小数点后两位。