Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Core EF, cleaning up SqlConnection.CreateCommand

I am using .NET Core DI to get DbContext and in my logic I need to execute raw SQL commands also on DB, so for that purpose I am creating DbCommand to execute SQL like this(just an example query, actual one is little complex so not writing here for simplicity):

public string GetId()
{
    var cmd = _context.Database.GetDbConnection().CreateCommand();

    bool isOpen = cmd.Connection.State == ConnectionState.Open;
    if (!isOpen)
    {
         cmd.Connection.Open();
    }

    cmd.CommandText = "Select TOP 1 ID from ABC;";
    var result = (string)cmd.ExecuteScalar();

    if (isOpen)
    {
         cmd.Connection.Close();
    }

    return result;
}

My question here is, that I am using GetDbConnection() and CreateCommand() on DbContext, so Do I need to explicitly dispose result of any of those commands(or enclose those in using statement)?

Also the if block to check if cmd.Connection.State is ConnectionState.Open required, if DI is providing with DbContext, that connection will already be open?

BTW we are using AddDbContextPool to register DbContext to enable DbContext pooling if that matters.

like image 480
Harshveer Singh Avatar asked Aug 25 '19 09:08

Harshveer Singh


1 Answers

My question here is, that I am using GetDbConnection() and CreateCommand() on DbContext, so Do I need to explicitly dispose result of any of those commands(or enclose those in using statement)?

These are different, and the answer is yes for the later, no for the former.

All you need is to follow to simple principle - the code which allocates resource is responsible for cleaning it up.

GetDbConnection (as indicated by the word Get) does not create DbConnection object, but returns the one created and used by the DbContext instance during its lifetime. In this case the DbContext owns the DbConnection, so you shouldn't dispose that object (doing so could break the owner functionality).

From the other side, CreateCommand does create new DbCommand object, so now your code is owning it and is responsible for disposing it when not needed anymore.

The same principle applies to Open / Close. Again, your code is not owning the DbConnection object, so you have to leave it in the same state as it was when you retrieved it. EF Core internally does that when processing commands which need open connection - open it at the beginning, close it when done. Except if it was opened externally, in which case they do nothing. Which is exactly the aforementioned principle - if your code does Open, then it should do Close, do nothing otherwise.

So the code in question should be something like this (note that there is a bug in close logic of your code - the condition for calling Close should be !isOpen, the same used for Open call):

public string GetId()
{
    using (var cmd = _context.Database.GetDbConnection().CreateCommand())
    {
        bool wasOpen = cmd.Connection.State == ConnectionState.Open;
        if (!wasOpen) cmd.Connection.Open();
        try
        {
            cmd.CommandText = "Select TOP 1 ID from ABC;";
            var result = (string)cmd.ExecuteScalar();
            return result;
        }
        finally
        {
            if (!wasOpen) cmd.Connection.Close();
        }
    }
} 
like image 60
Ivan Stoev Avatar answered Oct 14 '22 05:10

Ivan Stoev