Does DbContext holds an opened connection during its life-cycle?

6.5k Views Asked by At

The question is pretty clear. Does DbContext hold an open connection during its life-cycle? What about EF core?

1

There are 1 best solutions below

1
On BEST ANSWER

As noted by others, no, it doesn't, unless you manually open the connection and pass it to DbContext constructor.

A concrete detailed answer can be found here https://stackoverflow.com/a/45330219/191148.

And the comment of @ajcvickers in https://github.com/aspnet/EntityFrameworkCore/issues/7810 clears it:

If EF creates the DbConnection object, then EF will ensure it is disposed when the DbContext is disposed. On the other hand, if some other code creates the DbConnection object and passes it to EF, then it is the responsibility of the other code to also dispose the connection appropriately.

Similar rules apply to opening and closing the connection. If EF opens the connection, then EF will close the connection when it is done with it. If your code opens the connection, then your code should close the connection.