实体框架“意外连接状态”例外 [英] Entity Framework "Unexpected Connection State" Exception

查看:2337
本文介绍了实体框架“意外连接状态”例外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经过三个小时的调试和搜索,我希望有人在这里有一个答案。实体框架(使用MySQL)如果我连续快速调用以下函数(例如,相距0.1秒),则会引发以下异常。


System.InvalidOperationException:意外的连接状态。当使用包装提供程序时,请确保在包装的DbConnection上实现StateChange事件。


但是,有时该功能无任何问题。第一个 ToList()调用中抛出异常:

  void InsertOrUpdateMaterials(List< Material> materials)
{
var id = GetUserId();
var materialIds = materials.Select(x => x.MaterialId).ToList();

//从DB中删除旧材料
var oldMaterials = Db.Materials.Where(p => p.CreatedBy == id&&
materialIds.Contains p.MaterialId))ToList(); // exception
Db.Materials.RemoveRange(oldMaterials);
Db.SaveChanges();

//将以前的材料替换为列表
中的新材料Db.Materials.AddRange(materials);
Db.SaveChanges();
}

奇怪的是,这个错误从未发生在开发服务器上,所以我研究了可能配置问题无效。



有时,实体框架会抛出:


系统.Data.Entity.Core.EntityCommandExecutionException:已经有一个与此Connection关联的开放DataReader必须先关闭。


再次指向到 ToList()调用。任何想法?

解决方案

对于可能有类似问题的其他人。基于上述注释,代码使用缓存的数据库上下文。创建数据库上下文之后,应用程序中安装了db-connection(无 StateChange 处理程序)。连接崩溃后,应用程序使用缓存的数据库上下文来执行一些操作。



创建一个新的数据库上下文解决了这个问题。 $ b

After three hours of debugging and searching, I'm hoping someone here has an answer. Entity Framework (using MySQL) throws the following exception if I call the following function quickly in succession (e.g. < 0.1 seconds apart).

System.InvalidOperationException: Unexpected connection state. When using a wrapping provider ensure that the StateChange event is implemented on the wrapped DbConnection.

However, sometimes the function works without any problems. The exception is thrown on the first ToList() call:

void InsertOrUpdateMaterials(List<Material> materials)
{
    var id = GetUserId();
    var materialIds = materials.Select(x => x.MaterialId).ToList();

    // Remove old materials from DB
    var oldMaterials = Db.Materials.Where(p => p.CreatedBy == id && 
            materialIds.Contains(p.MaterialId)).ToList(); // exception
    Db.Materials.RemoveRange(oldMaterials);
    Db.SaveChanges();

    // Replace previous materials with the new ones in list
    Db.Materials.AddRange(materials);
    Db.SaveChanges();
}

Oddly, this error never occurred on the development server, so I looked into possible configuration issues to no avail.

Sometimes, Entity Framework throws:

System.Data.Entity.Core.EntityCommandExecutionException: There is already an open DataReader associated with this Connection which must be closed first.

Again pointing to the ToList() call. Any ideas?

解决方案

For other people that might a similar problem. Based on the above comments it seems that the code uses a cached db-context. After the db-context was created the db-connection broke (no StateChangehandler was installed in the application). After the connection breakdown the application used the cached db-context to perform some operations on it.

Creating a new db-context solved the problem.

这篇关于实体框架“意外连接状态”例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆