Must I use "Using" block in Entity Framework 6 for DbContext

c# dbcontext entity-framework entity-framework-6

Question

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?

1
3
7/10/2018 10:07:55 AM

Popular Answer

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.

1
11/11/2019 10:19:11 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow