gpt4 book ai didi

entity-framework - EntityFramework 上下文处置

转载 作者:行者123 更新时间:2023-12-03 07:25:47 24 4
gpt4 key购买 nike

我编写了几个与 Entity Framework 一起使用的应用程序。我曾经使用 using 子句。通过这个子句,我确信数据库连接已正确关闭。

但是,在某些情况下,我的数据库上下文对象是类的字段。它的实例化在声明中,并且没有using子句。

我刚刚发现,在这种情况下,Dispose() 方法没有被调用。使用 using 子句,会自动调用 Dispose()

所以我的问题是:如果没有在数据库上下文中调用 Dispose() 会发生什么?析构函数被调用,那么您认为析构函数会关闭数据库吗?或者我应该在容器对象的析构函数上手动调用 Dispose() ,如下所示:

class MyClass
{
public MyDbContext ctx = new MyDbContext();

....

~MyClass()
{
ctx.Dispose();
}
}

谢谢

最佳答案

绝对不能调用 Dispose。特别明确

当您使用using时,它是try-finally block 中的隐式Dispose()。这很好。但是您不需要明确地这样做。

为什么?

发生异常时,单独显式 Dispose语句可能会被错过发生更早。因此无法保证显式 Dispose

这是来自Rowan Miller [MSFT]:

The default behavior of DbContext is that the underlying connection is automatically opened any time is needed and closed when it is no longer needed. E.g. when you execute a query and iterate over query results using “foreach”, the call to IEnumerable.GetEnumerator() will cause the connection to be opened, and when later there are no more results available, “foreach” will take care of calling Dispose on the enumerator, which will close the connection. In a similar way, a call to DbContext.SaveChanges() will open the connection before sending changes to the database and will close it before returning.

Given this default behavior, in many real-world cases it is harmless to leave the context without disposing it and just rely on garbage collection.

That said, there are two main reason our sample code tends to always use “using” or dispose the context in some other way:

  1. The default automatic open/close behavior is relatively easy to override: you can assume control of when the connection is opened and closed by manually opening the connection. Once you start doing this in some part of your code, then forgetting to dipose the context becomes harmful, because you might be leaking open connections.

  2. DbContext implements IDiposable following the recommended pattern, which includes exposing a virtual protected Dispose method that derived types can override if for example the need to aggregate other unmanaged resources into the lifetime of the context.

您可以在这里阅读更多相关信息:Do I always have to call Dispose() on my DbContext objects? Nope

Managing DbContext the right way with Entity Framework

关于entity-framework - EntityFramework 上下文处置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39526038/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com