RepoDB
RepoDB copied to clipboard
Question: When to explicitly use .Open() or .EnsureOpen()
I am a bit confused when to use .Open() or even .EnsureOpen() on connections. Most of the documentation shows:
using (var connection = new MySqlConnection(ConnectionString))
{
var id = connection.Insert(person);
}
When using the Repositories you don't see any connection made (as it is in the base code of the Repository). But even there you don't find the EnsureOpen.
However, in a lot of Unit Tests you see the EnsureOpen called.
The only place were EnsureOpen is used is here:
https://github.com/mikependon/RepoDB.NET/blob/2a6f2e18cf7fecd99b8952b4d75834789ed3217c/pages/features/transaction.md
Could you explain when to use EnsureOpen please?
@stefandevo - practically, the EnsureOpen() is calling the Open() underneath only if the state of the connection object is not equals to ConnectionState.Open. It returns the IDbConnection instance itself.
In this regards, the most common use-case is to simply eliminate the line of code as it can be wrapped with the using keyword. (see sample below)
using (var connection = new MySqlConnection("...").EnsureOpen())
{
...
}
That's how we usually use this method.
On top of that, to ensure a seemless experience, all the operations of RepoDB is calling the EnsureOpen() method internally.
(Here is one of the actual call, from the Insert operation.)
When using the Repositories you don't see any connection made (as it is in the base code of the Repository). But even there you don't find the EnsureOpen.
The calls to the EnsureOpen() will never be visible to the repositories due to the fact that both the DbRepository and BaseRepository is abstracting the IDbConnection which also has the extended method implementations that do the calls. (The calls are happening behind the scene as explained above)
However, in a lot of Unit Tests you see the EnsureOpen called.
It all depends in your preference, but this should not be required.
The only place were EnsureOpen is used is here: https://github.com/mikependon/RepoDB.NET/blob/2a6f2e18cf7fecd99b8952b4d75834789ed3217c/pages/features/transaction.md
It is because creating a transaction object requires an opened connection.