当我第二次执行 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/