Search code examples
c#using

Scope of using statement


I have a method that gives me a list of objects e.g.

public IEnumerable<Person> GetPerson()
{
    using (myEntities ctx = new myEntities())
    {
        return ctx.Person.Where(x => x.Age < 50);
    }
}

somewhere else i use this method

public void Main()
{
   var pList = GetPerson();
   pList = pList.Where(x => x.Age < 40);

   Person Item = pList.FirstOrDefault(); //materialization here
}

When i call FirstOrDefault() the select is being genereated and the data is being retrieved from the database.

Question: is the scope of using (myEntities ctx = new myEntities()) reaching to the materialization?

On the one hand it schuld be because it manages the select/connection to the database and that is generated at materialization - on the other hand it's called outside of the method and that could be anywhere in the code - outside the using directives


Solution

  • No, the using statement does not survive all the way out to your materialization of the query.

    Unless calling Person already returns a fully materialized collection, which is unlikely and not typical.

    What happens is the following:

    1. You construct the context
    2. You call the Person property of the context, and tuck on a LINQ query

      Likely this will return a deferred query, which has not yet executed

    3. You dispose of the context
    4. You return the LINQ query you constructed
    5. You call FirstOrDefault on the query, attempting to execute it

    At this point the likely result is that the code crashes because you're trying to execute a query using a context which has been disposed.