Query with Include and FirstOrDefault() results in data reader being left open #3753
Closed
Description
DNX: 1.0.0-rc2-16117
EF: 1.0.0-rc2-16332
Running a query with FirstOrDefault
and Include
together doesn't seem to close the data reader.
var forums = _context.Forums.Include(f => f.Topics).FirstOrDefault();
var topics = _context.Topics.ToList();
The first query runs, however the second query errors with:
fail: Microsoft.Data.Entity.Query.Internal.SqlServerQueryCompilationContextFactory[1]
An exception occurred in the database while iterating the results of a query.
System.InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.
at System.Data.SqlClient.SqlInternalConnectionTds.ValidateConnectionForExecute(SqlCommand command)
at System.Data.SqlClient.SqlConnection.ValidateConnectionForExecute(String method, SqlCommand command)
at System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader()
at Microsoft.Data.Entity.Storage.Internal.RelationalCommand.<>c__DisplayClass17_0.<ExecuteReader>b__0(DbCommand cmd, IRelationalConnection con)
at Microsoft.Data.Entity.Storage.Internal.RelationalCommand.Execute[T](IRelationalConnection connection, Func`3 action, String executeMethod, Boolean openConnection, Boolean closeConnection, IReadOnlyDictionary`2 parameterValues)
at Microsoft.Data.Entity.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, Boolean manageConnection, IReadOnlyDictionary`2 parameterValues)
at Microsoft.Data.Entity.Query.Internal.QueryingEnumerable.Enumerator.MoveNext()
at Microsoft.Data.Entity.Query.QueryMethodProvider.<_ShapedQuery>d__3`1.MoveNext()
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at Microsoft.Data.Entity.Query.Internal.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext()
Interestingly, it does not error when Include
is not used:
//I run fine
var forums = _context.Forums.FirstOrDefault();
var topics = _context.Topics.ToList();
If you call ToList
and then FirstOrDefault
it seems to work fine as well:
//I also run fine
var forums = _context.Forums.Include(f => f.Topics).ToList().FirstOrDefault();
var topics = _context.Topics.ToList();
Repro example if it helps: https://github.com/davezych/EF7_3029/blob/FirstOrDefault/src/EF7_3029/Controllers/HomeController.cs
Activity