EntityFramework Context

I have written several applications that work with entity infrastructure. I used to work using a sentence. With this suggestion, I am sure that the database connection is closed properly.

But in some cases, my database context object is a class field. Its instantiation is contained in the declaration, and there is no suggestion for use.

I just found that in this case the Dispose () method is not called. When using a clause, Dispose () is called automatically

So my question is: what happens if Dispose () is not called in the context of the database? The destructor is called what do you think the database will be closed by the destructor? Or I have to call Dispose () manually in the destructor of the container object as follows:

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

    ....

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

thank

+4
2

Dispose . explicitly.

using, implicit Dispose() try-finally. . explicitly.

?

A separate explicit Dispose statement can be missed, exception earlier. explicit Dispose.

Rowan Miller [MSFT]:

DbContext , , . . "foreach", IEnumerable.GetEnumerator() , , "foreach" Dispose on , . , DbContext.SaveChanges() .

, , .

, , "" - :

  • / : , . - , , .

  • DbContext IDiposable , Dispose, , , , .

: Dispose() DbContext?

DbContext Entity Framework

+4

using , IDisposable:

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

    ....

    public void Dispose()
    {
        ctx.Dispose();
    }
}

, using .

+1

Source: https://habr.com/ru/post/1654776/