I’m wondering what the difference between…
using (var db = new PteDotNetContext())
{
var blog = new Blog() { BlogType = 1, Title = "Blog 1", Description = TestInfo.UniqueRecordIdentifier, DateAdded = DateTime.Now, User = TestInfo.UniqueRecordIdentifier };
db.Blogs.Add(blog);
db.SaveChanges();
}
PteDotNetContext context2 = new PteDotNetContext();
var blog2 = new Blog() { BlogType = 1, Title = "Blog 2", Description = TestInfo.UniqueRecordIdentifier, DateAdded = DateTime.Now, User = TestInfo.UniqueRecordIdentifier };
context2.Blogs.Add(blog2);
context2.SaveChanges();
is. I understand that using a using statement basically calls the destructor on the object. I just wonder…
a) Does the using statement open and then close a Sql connection on the DbContext?
b) If so what happens with the second statement because i never actually opened it and it still works. So when do I close the statement?
The variable declared inside
usingstatement is Disposed when using block is ended. On DbContext the disposal method closes the connection, so as soon as that code block is ended the connection is closed.Garbage collector clears the context object when it is no longer needed and the connection is being closed then.
You should read about
usingstatement andIDisposable.