Use of the using and DBContext
c#
Solution
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.
Problem
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