TransactionScope and SQLite database gets locked

我的梦境 提交于 2019-12-01 17:23:45

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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!