Search code examples
c#.netentity-frameworkidisposable

Disposing EntityConnection disposes also DbConnection within?


in my project I am using one of the overloads for instantiating EntityConnection.

internal static EntityConnection GetEntityConnection(string name)
{

    metadataWorkspace = new MetadataWorkspace(...);

    var connection = new SqlConnection(GetConnection(name));
    connection.AccessToken = OptionalAccessToken(connection);
    if (connection.State != ConnectionState.Open)
    {
        connection.Open();
    }

    using (var ec = new EntityConnection(metadataWorkspace, connection))
    {
        return ec;
    }
}

I am wondering, when the EntityConnection instance gets disposed automatically thanks to the usage of using does also the open connection within get disposed?


Solution

  • The answer to your question lies in the reflecting of the EntityConnection. Look into that and see for yourself, if underlying connection gets disposed. Many objects do something like that

    public void Dispose()
    {
        // dispose underlying objects
        _privateMemeber.Dispose();
    }
    

    For example, there was such a bug in MySql .NET provider.

    But the general rule should be, "if you have not created it, you don't dispose it". In your case, using should be used outside of GetEntityConnection

    using (var ec = new GetEntityConnection(...))
    

    After you research, if EntityConnection disposes underlying object, that should be enough.

    Otherwise you need to create disposing hierarchy

    using (var conn = new GetConnection(...))
    using (var enConn = new GetEntityConnection(...))
    {
       . . . .  .
    }