1

I have unit tests where I am creating and seeding a SQLCE4 database prior to each test method.

In the test method if I have a query like this:

var maxGroupLevel = repository.Get<GroupLevel>().Max(g => g.Id);

It will throw the exception below:

System.ObjectDisposedException: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
Result StackTrace:  
at System.Data.Objects.ObjectContext.EnsureConnection()
   at System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
   at System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator()
   at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)
   at System.Data.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__3[TResult](IEnumerable`1 sequence)
   at System.Data.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable`1 query, Expression queryRoot)
   at System.Data.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[S](Expression expression)
   at System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression)
   at System.Linq.Queryable.Max[TSource,TResult](IQueryable`1 source, Expression`1 selector)

However, if I put a ToList() call in the query it works:

var maxGroupLevel = repository.Get<GroupLevel>().ToList().Max(g => g.Id);

Whats going on?

Also, if I move the creation/seeding of the database to the constructor instead of the TestInitialize method and create a new context in TestInitialize then it all works ok. However, I don't want to do this as I want the database in a known state before each test.

user380689
  • 1,766
  • 4
  • 26
  • 39

2 Answers2

2

Your first version of the code is deferred until the first time maxGroupLevel is queried

var maxGroupLevel = repository.Get<GroupLevel>().Max(g => g.Id);

The second version of the code runs the query there and then so somewhere in between the above code and the first reference to maxGroupLevel the context is being disposed. Without visibility of the rest of your code it's harder to help than this.

qujck
  • 14,388
  • 4
  • 45
  • 74
0

Without looking into rest of the code it hard to identify exact problem. But you might want to know two things when working with Entity Framework related to ObjectDisposedException exception.

1) The data context must not be disposed of until all the data is fetched from the database.

2) A linq statement creates an IQueryable, which is not executed until you enumerate over it
(e.g. use it in a for each loop) or convert it to a list or an array.

Sundeep
  • 27
  • 3