I am trying to use Entity Framework 6 with SQLite and running into a database locked issue when trying to use TransactionScope
. Here is my code:
I was experiencing a similar issue. Just to be clear, the error I got on the second query was "the underlying provider failed on Open" (but the reason for the Open failure was that the database was locked).
Apparently the issue is related to MSDTC (TransactionScope
is tightly coupled to MSDTC).
I found a community addition to an MSDN page which in turn references this blog post
... which states that transactions are "promoted" to MSDTC transactions if a connection is closed and reopened. Which EF does by default. Normally this is a good thing -- you don't want database handles hanging around forever -- but in this case that behavior gets in the way.
The solution is to explicitly open the database connection:
using (var txn = new TransactionScope())
{
using (var ctx = new CalibreContext())
{
ctx.Connection.Open();
// ... remainder as before ...
Alternatively, if all your CalibreContext
objects are short-lived, you could conceivably open the connection in the CalibreContext
constructor.
This seems to have fixed my issue. I'll post an update if I have anything else to report.
One common situation to cause this problem is that another application is accessing the same database.
In my situation it’s because that I opened the database with DB Browser for SQLite, deleted a database table and not applying the changes.
Clicking Write Changes (or Revert Changes or Close Database) and the error will be gone.
(Taken from http://redino.net/blog/2017/03/net-sqlite-database-locked)