【问题标题】:EF6 - There is already an open DataReader associated with this Command which must be closed firstEF6 - 已经有一个打开的 DataReader 与此命令关联,必须先关闭
【发布时间】:2014-09-19 09:33:11
【问题描述】:

我正在编写 MVC5 互联网应用程序并使用 EF6。

我有一个 Edit ActionResult 在编辑 Asset 对象时调用。我还需要在编辑 Asset 对象时更新其他对象的值。 UpdateAssociatedAssetObjects 函数就是这样做的。

我收到以下错误:

There is already an open DataReader associated with this Command which must be closed first.

UpdateAssociatedAssetObjects 函数中,在以下代码行:

if (item.mapMarker.Id == asset.Id)

这里是Edit ActionResult

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit(AssetViewModel assetViewModel)
{
    if (ModelState.IsValid)
    {
        db.Entry(assetViewModel.asset).State = EntityState.Modified;
        assetViewModel.asset.lastUpdate = DateTime.Now;
        if (assetViewModel.asset.linkFromExternalResource)
        {
            assetViewModel.asset.webAddress = assetViewModel.webAddress;
        }
        else
        {
            assetViewModel.asset.webAddress = assetViewModel.filename;
        }
        db.Entry(assetViewModel.asset).Property(uco => uco.creationDate).IsModified = false;
        db.Entry(assetViewModel.asset).Property(uco => uco.userName).IsModified = false;
        assetService.UpdateAssociatedAssetObjects(db, assetViewModel.asset);
        await db.SaveChangesAsync();
        return RedirectToAction("Index");
    }
    return View(assetViewModel);
}

这是UpdateAssociatedAssetObjects函数:

public void UpdateAssociatedAssetObjects(CanFindLocationDatabaseContext db, Asset asset)
{
    foreach (var item in db.mapLocations)
    {
        if (item.mapMarker.Id == asset.Id)
        {
            item.lastUpdate = DateTime.Now;
        }
    }
}

我可以就这段代码寻求帮助吗?

我尝试将UpdateAssociatedAssetObjects 函数放在await db.SaveChangesAsync() 之后并使用新的数据库上下文对象,但错误仍然存​​在。

提前致谢

【问题讨论】:

  • 连接字符串是什么样的?
  • 连接字符串一切正常。已成功添加和删除对象。您认为问题出在连接字符串上吗?
  • 也许,这就是我问的原因:)
  • 你能帮忙解决 OP 中的问题吗?
  • 为什么不显示连接字符串?

标签: exception asp.net-mvc-5 entity-framework-6 datareader actionresult


【解决方案1】:

在您的控制器方法中,您已经打开了到资产条目的数据库连接。

在您的方法 UpdateAssociatedAssetObjects 中,您试图打开第二个数据库连接读取,而您的主要仍然是打开的。获取第一个对象或获取第二个对象中的列表。

另一种解决方案是更新数据库两次。

【讨论】:

    猜你喜欢
    • 2011-08-29
    • 1970-01-01
    • 2012-02-19
    • 1970-01-01
    • 2017-07-15
    • 1970-01-01
    相关资源
    最近更新 更多