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

前端 未结 18 2318
孤街浪徒
孤街浪徒 2020-11-22 01:40

I have this query and I get the error in this function:

var accounts = from account in context.Accounts
               from guranteer in account.Gurantors
           


        
相关标签:
18条回答
  • 2020-11-22 02:17

    As a side-note...this can also happen when there is a problem with (internal) data-mapping from SQL Objects.

    For instance...

    I created a SQL Scalar Function that accidentally returned a VARCHAR...and then...used it to generate a column in a VIEW. The VIEW was correctly mapped in the DbContext...so Linq was calling it just fine. However, the Entity expected DateTime? and the VIEW was returning String.

    Which ODDLY throws...

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

    It was hard to figure out...but after I corrected the return parameters...all was well

    0 讨论(0)
  • 2020-11-22 02:19

    You can use the ToList() method before the return statement.

    var accounts =
    from account in context.Accounts
    from guranteer in account.Gurantors
    
     select new AccountsReport
    {
        CreditRegistryId = account.CreditRegistryId,
        AccountNumber = account.AccountNo,
        DateOpened = account.DateOpened,
    };
    
     return accounts.AsEnumerable()
                   .Select((account, index) => new AccountsReport()
                           {
                               RecordNumber = FormattedRowNumber(account, index + 1),
                               CreditRegistryId = account.CreditRegistryId,
                                  DateLastUpdated = DateLastUpdated(account.CreditRegistryId, account.AccountNumber),
                               AccountNumber = FormattedAccountNumber(account.AccountType, account.AccountNumber)}).OrderBy(c=>c.FormattedRecordNumber).ThenByDescending(c => c.StateChangeDate).ToList();
    
    
     public DateTime DateLastUpdated(long creditorRegistryId, string accountNo)
        {
            var dateReported = (from h in context.AccountHistory
                                where h.CreditorRegistryId == creditorRegistryId && h.AccountNo == accountNo
                                select h.LastUpdated).Max();
            return dateReported;
        }
    
    0 讨论(0)
  • 2020-11-22 02:19

    In my case, I had to set the MultipleActiveResultSets to True in the connection string.
    Then it appeared another error (the real one) about not being able to run 2 (SQL) commands at the same time over the same data context! (EF Core, Code first)
    So the solution for me was to look for any other asynchronous command execution and turn them to synchronous, as I had just one DbContext for both commands.

    I hope it helps you

    0 讨论(0)
  • 2020-11-22 02:21

    I had the same error, when I tried to update some records within read loop. I've tried the most voted answer MultipleActiveResultSets=true and found, that it's just workaround to get the next error 

    New transaction is not allowed because there are other threads running in the session

    The best approach, that will work for huge ResultSets is to use chunks and open separate context for each chunk as described in  SqlException from Entity Framework - New transaction is not allowed because there are other threads running in the session

    0 讨论(0)
  • 2020-11-22 02:24

    Here is a working connection string for someone who needs reference.

      <connectionStrings>
        <add name="IdentityConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\IdentityDb.mdf;Integrated Security=True;MultipleActiveResultSets=true;" providerName="System.Data.SqlClient" />
      </connectionStrings>
    
    0 讨论(0)
  • 2020-11-22 02:26

    I solved this problem by changing await _accountSessionDataModel.SaveChangesAsync(); to _accountSessionDataModel.SaveChanges(); in my Repository class.

     public async Task<Session> CreateSession()
        {
            var session = new Session();
    
            _accountSessionDataModel.Sessions.Add(session);
            await _accountSessionDataModel.SaveChangesAsync();
         }
    

    Changed it to:

     public Session CreateSession()
        {
            var session = new Session();
    
            _accountSessionDataModel.Sessions.Add(session);
            _accountSessionDataModel.SaveChanges();
         }
    

    The problem was that I updated the Sessions in the frontend after creating a session (in code), but because SaveChangesAsync happens asynchronously, fetching the sessions caused this error because apparently the SaveChangesAsync operation was not yet ready.

    0 讨论(0)
提交回复
热议问题