When you put an object in a using()
statement, it "disposes" the object when the block is exited. This is so that the object can clean up things like database connections. Once the object has been disposed, it can no longer be used and you'll need to create a new one.
It looks like db
is a variable that you are creating once and holding onto - but after the using
statement disposes of it, it cannot be used again. Modify your code so that you create a new data context each time you access the database, like this:
using (DatabaseContext db = new DatabaseContext())
{
... // Do things here
}
Whenever you use a using
statement, declare the object inside the statement. This is especially true for database transactions, since you can run into major issues with concurrency and caching later on if you hang onto the same context. Keep your contexts localized and dispose of them as soon as you are done with a transaction.