'System.Data.IDbConnection' to 'System.Data.SqlClient.SqlConnection'

.net, c#

Solution

Th error message is self explanatory. Your method takes an `IDBTransaction`, it's `Connection` property returns `IDBConnection` which is an interface that all connection types implement, not only `SqlConnection`.

You could cast it to `SqlConnection` but that would be error-prone if someone tries to use your method with a different transaction type since that results in a runtime exception..

But you can use `Connection.CreateCommand`:

protected override IDbCommand GetDbCommand(string key, IDbTransaction transaction)
{
    if (transaction == null)
    {
        return base.GetDbCommand(key);
    }
    var cmd = transaction.Connection.CreateCommand(); 
    cmd.Transaction = transaction; 
    return cmd;
}

Problem

``` protected override IDbCommand GetDbCommand(string key, IDbTransaction transaction) { if (transaction == null) { return base.GetDbCommand(key); } return new SqlCommand { Connection = transaction.Connection, Transaction = transaction }; } ``` I am getting the following error when trying to complile the above code. Cannot implicitly convert type 'System.Data.IDbConnection' to 'System.Data.SqlClient.SqlConnection'. An explicit conversion exists (are you missing a cast?)

Original source