5

This is question is not about the "Using" in general of c#, and not about when/why to use it etc..

The question is, does the DBContext object dispose the connection by itself, and therefore I don't need to use using to make it dispose, there is no question about it so don't mark it as duplicated

using (DBContext db = new DBContext())
{
    var Order =  db.Order.First(r => r.OrderID == 6);
    Order.Type = 6;
    db.SaveChanges();
}

Or without using

DBContext db = new DBContext();
var Order =  db.Order.First(r => r.OrderID == 6);
Order.Type = 6;
db.SaveChanges();

Because I see in this source that using is not necessary and it's better not to use it.

Will Entity Framework dispose the connection for me?

Daz
  • 2,438
  • 1
  • 16
  • 23
Daniel Ezra
  • 1,264
  • 3
  • 13
  • 21
  • One of the impacts of using is when you are dealing with eager loading and lazy loading. Check the last part of this answer for more details https://stackoverflow.com/a/34628138/2946329 – Salah Akbari Jul 10 '18 at 09:37

1 Answers1

2

The lifetime of the context begins when the instance is created and ends when the instance is either disposed or garbage-collected. Use using if you want all the resources that the context controls to be disposed at the end of the block.

When you use using, the compiler automatically creates a try/finally block and calls dispose in the finally block.

ammu
  • 238
  • 3
  • 9