user5997884
user5997884

Reputation: 157

Is it valid to use an EF-linq-query-result after the DbContext is disposed?

I have all logic functions inside the using-DbContext scope. For future code I want to write (and maybe refactoring) I considered to change it into this form, where I load the list using the context, and dispose it immediately after it and use the list for further computations.

Test()
{
    var list = (List<MyObject>)null;

    using( var ctx = new MyDbContext() )
    {
        list = ctx.MyTable.ToList();
    }

    // is the list guaranteed to be unchanged?
    foreach( var item in list )
    {

    }
}

The only difference (as I would guess) is that the EF dropped the cache for the objects, so I cannot update the database anylonger (what I usually do not want/use anyways).

Is it safe to use the list after the context has been disposed?

Upvotes: 0

Views: 51

Answers (1)

gmn
gmn

Reputation: 4319

Short answer, Yes. Once you call ToList() the object should be detached from EF but will still have any tracking proxies attached to it that have been defined by EF.

No EF stuff will work on it though, like Lazy loading etc...

Upvotes: 1

Related Questions