Search code examples
c#vb.netentity-framework-4entity-framework-6dbcontext

What DBContext is being invoked when using Dim Results = Me.Objects


Hi I am using Entity Framework in a .net project, and I have previously retrieved results using syntax like this:

Using Context As New Model.DbContext
            Dim Results = From X In Context.MyObjects.ToList
End Using

I have read that creating and destroying the DbContext object as required instead of maintaning a long running context is the preferred pattern.

So when I have an entity and I call something like:

Dim Results = Me.MyObjects.ToList

how does that work? Is there some implicit creation of a context under the covers?

And secondly, if so, is it computationally expensive to be creating and tearing down this context every time I get properties from an object in this way? Does this keep hitting the database? I presume objects are not cached as they would be with a global context that is kept open.

Any thoughts would be appreciated!


Solution

  • For the performance question. It's answered here. Is DbContext an expensive operation?

    As for the MyObjects.ToList, it looks like it automatically handles the "context creation". http://blog.jongallant.com/2012/10/do-i-have-to-call-dispose-on-dbcontext.html#.U6WdzrGEeTw