Search code examples
asp.net-mvc-3linqlinq-to-sqlobjectdisposedexception

ObjectDisposedException after returning from LINQ to SQL query


I am using MVC3 with .NET 4.0 and when my create form is invoked I get an ObjectDisposedException saying that the object has been disposed. The exception ocurrs on this MVC3 page statement:

@Html.DropDownListFor(model => model.Country, GeneralActivity.GetCountriesMVC("NL"))

And the invoked method is like this:

IEnumerable<SelectListItem> GetCountriesMVC(string preselectCountryCode)
{
   ... some error checking code omited for simplicity ...
   IEnumerable<SelectListItem> qlist;
   using (Data.MyDataContext ctx = new Data.MyDataContext()) {
      qlist = from p in ctx.Countries select new SelectListItem {
          Text = p.CountryName,
          Value = p.CountryCodeId,
          Selected = (p.CountryCodeId == preselectCountryCode)
      };
   }
   return qlist;
}

During debug I execute up to the return statement and then it leaves and brings me to the invoking @Html statement on the MVC page and the exception is thrown.

The qlist instance is declared outside the USING statement and initialized by the LINQ query so I don't see why it says the object has been disposed.


Solution

  • You're not actually executing the query - so when you try to access the qList it's attempting to connect back to your database, and the connection is closed.

    Try casting your query to a list so it will be stored in memory:

     qlist = (from p in ctx.Countries select new SelectListItem {
          Text = p.CountryName,
          Value = p.CountryCodeId,
          Selected = (p.CountryCodeId == preselectCountryCode)
      }).ToList();