c# - using和DBContext的使用

标签 c#

我确保完全理解以下代码:

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/

相关文章:

c# - 如何将项目插入带有星标的数据库?

c# - 如何在 WPF 中围绕文本 block 的背景矩形定义描边?

c# - 如何删除所有隐藏的元素?

c# - 如何截取后台进程的屏幕截图?

c# - 系统参数异常 : Parameter is not valid

c# - 下载大文件

c# - 从 .CS 代码文件中提取方法名称

c# - vb.Net c# 运行批处理文件并流式传输其输出

c# - 数据驱动测试消除空白

'all methods' 的 C# 委托(delegate)或 Func?