DbContext
does not open the connection when you initialize it.
DbContext
opens and closes the connection for every operation you execute eg. any query or a call to SaveChanges
.
If you want to control when the connection is open or closed you will have to pass your own connection and specify that the context does not own this connection by using the overloaded constructor: public DbContext(DbConnection existingConnection, bool contextOwnsConnection)
And to answer your question, YES, you still need to use a using
block or call Dispose to free any unmanaged resource. Remember that EF uses ADO.NET and this one invokes many unmanaged APIs under the hood.
hope this helps
UPDATE:
In order to verify all this create/add a new constructor for your context:
public class TestDbContext : DbContext
{
public TestDbContext(DbConnection connection, bool contextOwnsConnection)
: base(connection, contextOwnsConnection) { }
}
Then use the same code you used in your example when calling SaveChanges()
var conn = new SqlConnection("your connection string here");
using (var ctx = new TestDbContext(conn, [false/true])) //play with true and false
{
conn.Open(); //you can also comment this to discover other situations
ctx.Items.Add(item);
ctx.SaveChanges();
throw new Exception(); //also comment this line and you will see the connection
//is still open because it is not controlled inside the
//DbContext
}
If you use true
for the second parameter in your context constructor you will notice that the connection is gone when your test finishes. This is the default behavior for a DbContext because the connection is created within and the context owns the connection (opens and closes as needed).
On the other hand if you use false
you will notice the connection is still open even when the context is disposed if the connection is opened by calling conn.Open()
. If the context calls conn.Open()
internally to execute any query or save changes the context will control when to open and close the connection.
You can play with the second Boolean parameter and the call to conn.Open()
to discover very interesting different scenarios.
The following example shows you that even when you created the connection manually, but since you didn't open it manually, the context will open and close automatically. The managed connection state is closed even before the exception is thrown and your native connection is still open.
var conn = new SqlConnection("your connection string here");
using (var ctx = new TestDbContext(conn, false))
{
//conn.Open();
ctx.Items.Add(item);
ctx.SaveChanges();
var state = conn.State
throw new Exception();
}