2

I am making sure to fully understand this following code:

static void Main(string[] args)
{
    var person = new Person {FirstName = "Nadege", 
    LastName = "Deroussen", BirthDate = DateTime.Now};
    using (var context = new MyContext())
    {
        context.Persons.Add(person);
        context.SaveChanges();
    }
    Console.Write("Person saved !");
    Console.ReadLine();
}

As you can see, using is follow by {}, Correct me if I am wrong, does it means the the context would be closed after the {} ? a DBContext should it be closed everytime such as this ?

Cheers all

dtjmsy
  • 2,664
  • 9
  • 42
  • 62

3 Answers3

8

Correct me if I am wrong, does it means the the context would be closed after the {} ?

It would be disposed, yes. Your code is effectively:

var context = new MyContext();
try
{
    context.Persons.Add(person);
    context.SaveChanges();
}
finally
{
    context.Dispose();
}

a DBContext should it be closed everytime such as this ?

Assuming this is LINQ to SQL, you don't actually need to dispose of the context. However, in general it's a good idea to dispose of anything which implements IDisposable - unless you actually know that you don't need to. (Basically there are some situations where the implementation of IDisposable is an inconvenient side-effect of something else.) Even in this case, I would continue to do so.

Community
  • 1
  • 1
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

Yes, DbContext will be closed. Refer to http://msdn.microsoft.com/en-us/library/yh598w02(v=vs.80).aspx for more details.

1

MyContext is derived from DBContext which derives from Disposable. You need to dispose your object when you are no longer using it. Using helps in this. You don't need to call context.Dispose() as using will call it itself.

It is good to use using as context is no valid after using block. If you don't use this and go for context.Dispose() and after then you call context, then exception will come. So it helps in better code management.

fhnaseer
  • 7,159
  • 16
  • 60
  • 112