试图关闭DataReader

时间:2017-05-17 06:56:34

标签: c# linq entity

尝试使用以下功能更新数据库。 但是当我试图运行这个函数时,它表示我没有关闭我的DataReader。 错误 - 已经有一个与此命令关联的打开DataReader,必须先关闭它。 想问一下我在哪里关闭它。谢谢。

private static void updateICAT(DataSet s)
    {
        DataTable excelTable = s.Tables[7];
        DataTable contacts = getXML();

        Context _db = new Context();
        var updateICAT = _db.ICATs;

        int counter = 1;

        foreach(ICAT icat in updateICAT)
        {

            if(icat.ICATName != "--NOT AVAILABLE--")
            {
                DataRow r = contacts.Select("ICATName='" + excelTable.Rows[counter].ItemArray[2].ToString().Trim() + "'")[0];
                if (icat.ICATName != excelTable.Rows[counter].ItemArray[0].ToString())
                {

                    System.Diagnostics.Debug.WriteLine("not match");
                    System.Diagnostics.Debug.WriteLine("current Icat id " + icat.ICATID + " current counter " + counter);
                    var updateCurrentICAT = updateICAT.SingleOrDefault(p => p.ICATID == counter);
                    updateCurrentICAT.ICATName = excelTable.Rows[counter].ItemArray[0].ToString().Trim();
                    updateCurrentICAT.MEGroup = excelTable.Rows[counter].ItemArray[1].ToString().Trim();
                    updateCurrentICAT.EscalationDisplayName = excelTable.Rows[counter].ItemArray[2].ToString().Trim();
                    updateCurrentICAT.EscalationUserName = r["Username"].ToString().Trim();
                    updateCurrentICAT.EscalationMail = r["Mail"].ToString().Trim();
                }
            }
            counter++;
        }
    }

错误已开启

 var updateCurrentICAT = updateICAT.SingleOrDefault(p => p.ICATID == counter);

下面是堆栈跟踪:

    [InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.]
   System.Data.SqlClient.SqlInternalConnectionTds.ValidateConnectionForExecute(SqlCommand command) +1543253
   System.Data.SqlClient.SqlConnection.ValidateConnectionForExecute(String method, SqlCommand command) +101
   System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async) +268
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) +91
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +53
   System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +161
   System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +41
   System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +12
   System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<Reader>b__c(DbCommand t, DbCommandInterceptionContext`1 c) +14
   System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch(TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed) +72
   System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext) +402
   System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior) +166
   System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +12
   System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) +36

[EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details.]
   System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) +103
   System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute(ObjectContext context, ObjectParameterCollection parameterValues) +758
   System.Data.Entity.Core.Objects.<>c__DisplayClass7.<GetResults>b__6() +90
   System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction(Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) +288
   System.Data.Entity.Core.Objects.<>c__DisplayClass7.<GetResults>b__5() +154
   System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func`1 operation) +190
   System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) +283
   System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0() +15
   System.Data.Entity.Internal.LazyEnumerator`1.MoveNext() +45
   System.Linq.Enumerable.SingleOrDefault(IEnumerable`1 source) +121
   System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__2(IEnumerable`1 sequence) +40
   System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle(IEnumerable`1 query, Expression queryRoot) +59
   System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute(Expression expression) +114
   System.Data.Entity.Internal.Linq.DbQueryProvider.Execute(Expression expression) +116
   System.Linq.Queryable.SingleOrDefault(IQueryable`1 source, Expression`1 predicate) +249
   WITS_v4.Pages.updateRecord.updateICAT(DataSet s) in C:\Users\khongkok\Source\Repos\WITS\WITS v4\Pages\updateRecord.aspx.cs:94
   WITS_v4.Pages.updateRecord.Page_Load(Object sender, EventArgs e) in C:\Users\khongkok\Source\Repos\WITS\WITS v4\Pages\updateRecord.aspx.cs:22
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
   System.Web.UI.Control.OnLoad(EventArgs e) +95
   System.Web.UI.Control.LoadRecursive() +59
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2952

1 个答案:

答案 0 :(得分:0)

我认为在LINQ IEnumerable foreach循环中使用updateICAT.SingleOrDefault会导致问题。解决此问题的一种方法是转换为使用第二个void sprint(char *filename, char * dirToOpen) { DIR *directory = opendir(dirToOpen); struct dirent *entry; struct stat s; char pathname[1024]; if (directory) { /*if it's a directory*/ while ((entry = readdir(directory)) != NULL) { /*while there are more entries to read*/ if(strcmp(entry->d_name, filename) == 0) /*if entry name corresponds to filename, print it*/ printf("%s\n", filename); sprintf(pathname, "./%s", entry->d_name); /*makes pathname*/ if (lstat(pathname, &s) == 0 && S_ISDIR(s.st_mode)) { /*if the file is a directory*/ if(strcmp(entry->d_name, "..") != 0 && strcmp(entry->d_name, ".") != 0) /*if the directory isn't . or ..*/ sprint(filename, entry->d_name); } } closedir(directory); } } 并在循环内调用Context,如下所示。

db2.ICATs.SingleOrDefault