none
EF implicit creation of a DBContext for entity queries? RRS feed

  • Question

  • 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!

    Tuesday, May 10, 2016 2:11 AM

Answers

  • Hi RKendal,

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

    it retrieves the data form database and adds to memory.

    >>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?

    Yes, The ToList() call is going to cause EF to pull all of the MyObjects records back from the DB.  Your call to the Where extension method will be run against the set in memory.

    Best regards,

    Cole Wu


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    • Marked as answer by RKendal Friday, May 13, 2016 1:59 AM
    Tuesday, May 10, 2016 6:13 AM
    Moderator