1

I have a method for starting a game written in MVC with Entity Framework and it's been over the Repository and Unit of works:

public Team StartTeam(Message message, out string result)
    {
        try
        {
            var player = GetPlayer(message);
            if (player.StatusId == (int)Status.Playing)
            {
                result = Mesages.CantStartGameDuringAnotherGame;
                return null;
            }
            var team = Uow.TeamContext.FindBy(q => q.Name == message.Text).FirstOrDefault();
            if (team == null)
            {
                result = Mesages.UnexpectedError;
                return null;
            }
            var members = Uow.MembershipContext.FindBy(q => q.TeamId == team.Id);
            var players = new List<Player>();
            foreach (var member in members.Where(q => q.PlayerId != player.Id))
            {
                var pl = Uow.PlayerContext.GetSingle(member.PlayerId);
                if (player.StatusId == (int)Status.Active)
                    players.Add(pl);
            }
            players.Add(player);
            player.StatusId = (int)Status.Active;
            if (players.Count < 2)
            {
                result = Mesages.NotEnoughPlayers;
                return null;
            }
            var race = new Race()
            {
                TeamId = team.Id,
                PlayDate = DateTime.Now
            };
            race = Uow.RaceContext.Add(race);
            Uow.Save();
            team.CurrentRaceId = race.Id;
            foreach (var playr in players)
            {
                playr.StatusId =
                    members.First(q => q.PlayerId == playr.Id).StatusId
                        = (int)Status.Playing;
                playr.CurrentTeamId = team.Id;
            }
            result = Mesages.TeamStartedSuccessfuly;
            player.StatusId = (int)Status.Playing;
            return team;
        }
        catch (Exception ex)
        {
            SaveException(ex);
            return null;
        }
    }

Every things seems to be ok and I can run it in my local but when I publish it I gave this error:

There is already an open  DataReader associated with this Command which must be closed first.

This is complete stack trace:

    System.Data.Entity.Core.EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details. ---> 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(CommandBehavior behavior)
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<Reader>b__c(DbCommand t, DbCommandInterceptionContext`1 c)
   at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)
   at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
   at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
   --- End of inner exception stack trace ---
   at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
   at System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)
   at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__6()
   at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
   at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__5()
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
   at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
   at System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
   at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
   at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)
   at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__1[TResult](IEnumerable`1 sequence)
   at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable`1 query, Expression queryRoot)
   at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
   at System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression)
   at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable`1 source, Expression`1 predicate)
   at EsmFamilWebHoook.Models.PlayerRepository.GetSingle(Int32 playerId)
   at EsmFamilWebHoook.DatabaseService.StartTeam(Message message, String& result)

What happened? I saw this post but not helped me!

Community
  • 1
  • 1
mani
  • 23
  • 1
  • 6

1 Answers1

0

Might be that your query:

var pl = Uow.PlayerContext.GetSingle(member.PlayerId);

is placed inside foreach which iterates over result of another query (but this query might still be active - may be it read just first batch of rows or it doing some lazy loading):

foreach (var member in Uow.MembershipContext.FindBy(q => q.TeamId == team.Id).Where(q => q.PlayerId != player.Id))

Try to force result of first query to be fully loaded into memory first using .ToArray() for example:

foreach (var member in Uow.MembershipContext.FindBy(q => q.TeamId == team.Id).Where(q => q.PlayerId != player.Id).ToArray())

Generally you can have 1 query active at time.

Honza
  • 335
  • 3
  • 14