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

前端 未结 18 2526
孤街浪徒
孤街浪徒 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:32

    It appears that you're calling DateLastUpdated from within an active query using the same EF context and DateLastUpdate issues a command to the data store itself. Entity Framework only supports one active command per context at a time.

    You can refactor your above two queries into one like this:

    return accounts.AsEnumerable()
            .Select((account, index) => new AccountsReport()
            {
              RecordNumber = FormattedRowNumber(account, index + 1),
              CreditRegistryId = account.CreditRegistryId,
              DateLastUpdated = (
                                                    from h in context.AccountHistory 
                                                    where h.CreditorRegistryId == creditorRegistryId 
                                  && h.AccountNo == accountNo 
                                                    select h.LastUpdated).Max(),
              AccountNumber = FormattedAccountNumber(account.AccountType, account.AccountNumber)
            })
            .OrderBy(c=>c.FormattedRecordNumber)
            .ThenByDescending(c => c.StateChangeDate);
    

    I also noticed you're calling functions like FormattedAccountNumber and FormattedRecordNumber in the queries. Unless these are stored procs or functions you've imported from your database into the entity data model and mapped correct, these will also throw excepts as EF will not know how to translate those functions in to statements it can send to the data store.

    Also note, calling AsEnumerable doesn't force the query to execute. Until the query execution is deferred until enumerated. You can force enumeration with ToList or ToArray if you so desire.

提交回复
热议问题