Entity Framework "Unexpected Connection State" Exception

c# entity-framework signalr


I've spent the last three hours debugging and looking, and I'm hoping someone here has the solution. If I use the following functions quickly and consecutively in Entity Framework (using MySQL), the following exception is raised (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, occasionally the feature operates without any issues. On the first try, the exception is raised.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

    // Replace previous materials with the new ones in list

Oddly, the development server never experienced this error, so I checked into potential setup problems in vain.

Entity Framework may occasionally throw:

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

highlighting once more theToList() Give me a call.

4/7/2016 5:12:43 PM

Popular Answer

For others who might be experiencing a similar issue. It appears from the remarks above that the function uses a cached database context. The database connection was lost once the db-context was created (noStateChange handler was added to the program). The program exploited the cached db-context to conduct certain operations on it after the connection failed.

A new db-context was created to resolve the issue.

4/29/2016 7:26:12 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow