TransactionScope and SQLite database gets locked

前端 未结 2 1501
一生所求
一生所求 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.

提交回复
热议问题