我确保完全理解以下代码:
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();
}
如您所见,using 后面跟着 {},如果我错了请纠正我,这是否意味着上下文将在 {} 之后关闭?像这样每次都应该关闭 DBContext 吗?
大家好
最佳答案
Correct me if I am wrong, does it means the the context would be closed after the {} ?
它会被处理掉,是的。您的代码有效:
var context = new MyContext();
try
{
context.Persons.Add(person);
context.SaveChanges();
}
finally
{
context.Dispose();
}
a DBContext should it be closed everytime such as this ?
假设这是 LINQ to SQL,you don't actually need to dispose of the context .但是,一般来说,处置任何实现了 IDisposable
的东西是个好主意 - 除非您实际上知道您不需要这样做。 (基本上在某些情况下,IDisposable
的实现是其他东西的不便副作用。)即使在这种情况下,我也会继续这样做。
关于c# - using和DBContext的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16162384/