Search code examples
c#dbcontextdisposeusinginvalidoperationexception

DbContext get's disposed within using region


I just found out that when I try to use the .Add() method on a DbSet in my DbContext I get the following exception:

System.InvalidOperationException : The operation cannot be completed because the DbContext has been disposed.

This stack trace brought me back to line 238 of this method: Method

Now it is true that this method uses two other methods (CheckForBleKeyInDb and CheckForMpSwitchInDb) which use their own using(_db = new BeheerContext()) but this doesn't generate any errors for some reason.

The test variables don't generate any exceptions probably because they don't actually connect to the database, at least that is my guess.

I would like to know what exactly causes this exception and how I can prevent it.


Solution

  • Don't use the context as field in your class, then all methods share it and will dispose it at the end of their using statements.

    Now it is true that this method uses two other methods (CheckForBleKeyInDb and CheckForMpSwitchInDb) which use their own using(_db = new BeheerContext()) but this doesn't generate any errors for some reason.

    So after the first call of those methods your context is disposed too.

    Instead create them in the method(var _db = ...):

    using(var _db = new BeheerContext())
    {
       //...
    }
    

    Your test variables don't generate exceptions because they don't select from the tables. You would get the same exception if you'd for example use

    var test1 = _db.BleKeys.First();