TransactionScope and SQLite database gets locked

前端 未结 2 1471
一生所求
一生所求 2021-01-18 11:02

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:



        
相关标签:
2条回答
  • 2021-01-18 11:44

    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.

    0 讨论(0)
  • 2021-01-18 11:58

    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)

    0 讨论(0)
提交回复
热议问题