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?

1
  • 1
    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 stackoverflow.com/a/34628138/2946329 Commented Jul 10, 2018 at 9:37

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.