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.