How can I use SqlBulkCopy from Entity Framework database connection in unknown state
<p>I have a static helper method for bulk inserting Entity Framework objects. It works and my unit tests pass but it looks wrong and I can't help but think there must be a better way to do it.</p>

<pre><code>public static void BulkInsert&lt;T&gt;(Entities db, IList&lt;T&gt; list)
{
    SqlTransaction transaction =  db.Database.CurrentTransaction != null ? db.Database.CurrentTransaction.UnderlyingTransaction as SqlTransaction : null;

    if (db.Database.Connection.State != ConnectionState.Open)
    {
        db.Database.Connection.Open();
    }

    using (var bulkCopy = new SqlBulkCopy((db.Database.Connection) as SqlConnection, SqlBulkCopyOptions.Default, transaction))
    {
        //fill a datatable and write to server, this bit works
    }
}
</code></pre>

<p>It could be called inside a <code>DbContextTransaction</code> and/or the <code>DbContext.Database</code> might have done something already so the connection might be open. If you don't explicitly open the connection before creating the bulk copy you get an error:</p>

<blockquote>
  <p>System.InvalidOperationException: WriteToServer requires an open and available Connection</p>
</blockquote>

<p>which is odd, I'd have thought that <code>sqlBulkCopy</code> would have opened the connection if it had to.</p>

<p>So my question is am I going about this the right way?</p>