已经有一个打开的 DataReader 与此命令关联,必须先将其关闭

发布于 2024-11-09 00:11:02 字数 4323 浏览 0 评论 0原文

我有这个查询,我在这个函数中收到错误:

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);


public DateTime DateLastUpdated(long creditorRegistryId, string accountNo)
{
    return (from h in context.AccountHistory
            where h.CreditorRegistryId == creditorRegistryId && h.AccountNo == accountNo
            select h.LastUpdated).Max();
}

错误是:

已经有一个与此命令关联的打开的 DataReader,必须先将其关闭。

更新:

添加了堆栈跟踪:

InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.]
   System.Data.SqlClient.SqlInternalConnectionTds.ValidateConnectionForExecute(SqlCommand command) +5008639
   System.Data.SqlClient.SqlConnection.ValidateConnectionForExecute(String method, SqlCommand command) +23
   System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async) +144
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +87
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +32
   System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +141
   System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +12
   System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +10
   System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) +443

[EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details.]
   System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) +479
   System.Data.Objects.Internal.ObjectQueryExecutionPlan.Execute(ObjectContext context, ObjectParameterCollection parameterValues) +683
   System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) +119
   System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator() +38
   System.Linq.Enumerable.Single(IEnumerable`1 source) +114
   System.Data.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__3(IEnumerable`1 sequence) +4
   System.Data.Objects.ELinq.ObjectQueryProvider.ExecuteSingle(IEnumerable`1 query, Expression queryRoot) +29
   System.Data.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute(Expression expression) +91
   System.Data.Entity.Internal.Linq.DbQueryProvider.Execute(Expression expression) +69
   System.Linq.Queryable.Max(IQueryable`1 source) +216
   CreditRegistry.Repositories.CreditRegistryRepository.DateLastUpdated(Int64 creditorRegistryId, String accountNo) in D:\Freelance Work\SuperExpert\CreditRegistry\CreditRegistry\Repositories\CreditRegistryRepository.cs:1497
   CreditRegistry.Repositories.CreditRegistryRepository.<AccountDetails>b__88(AccountsReport account, Int32 index) in D:\Freelance Work\SuperExpert\CreditRegistry\CreditRegistry\Repositories\CreditRegistryRepository.cs:1250
   System.Linq.<SelectIterator>d__7`2.MoveNext() +198
   System.Linq.Buffer`1..ctor(IEnumerable`1 source) +217
   System.Linq.<GetEnumerator>d__0.MoveNext() +96

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

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);


public DateTime DateLastUpdated(long creditorRegistryId, string accountNo)
{
    return (from h in context.AccountHistory
            where h.CreditorRegistryId == creditorRegistryId && h.AccountNo == accountNo
            select h.LastUpdated).Max();
}

Error is:

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

Update:

stack trace added:

InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.]
   System.Data.SqlClient.SqlInternalConnectionTds.ValidateConnectionForExecute(SqlCommand command) +5008639
   System.Data.SqlClient.SqlConnection.ValidateConnectionForExecute(String method, SqlCommand command) +23
   System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async) +144
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +87
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +32
   System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +141
   System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +12
   System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +10
   System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) +443

[EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details.]
   System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) +479
   System.Data.Objects.Internal.ObjectQueryExecutionPlan.Execute(ObjectContext context, ObjectParameterCollection parameterValues) +683
   System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) +119
   System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator() +38
   System.Linq.Enumerable.Single(IEnumerable`1 source) +114
   System.Data.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__3(IEnumerable`1 sequence) +4
   System.Data.Objects.ELinq.ObjectQueryProvider.ExecuteSingle(IEnumerable`1 query, Expression queryRoot) +29
   System.Data.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute(Expression expression) +91
   System.Data.Entity.Internal.Linq.DbQueryProvider.Execute(Expression expression) +69
   System.Linq.Queryable.Max(IQueryable`1 source) +216
   CreditRegistry.Repositories.CreditRegistryRepository.DateLastUpdated(Int64 creditorRegistryId, String accountNo) in D:\Freelance Work\SuperExpert\CreditRegistry\CreditRegistry\Repositories\CreditRegistryRepository.cs:1497
   CreditRegistry.Repositories.CreditRegistryRepository.<AccountDetails>b__88(AccountsReport account, Int32 index) in D:\Freelance Work\SuperExpert\CreditRegistry\CreditRegistry\Repositories\CreditRegistryRepository.cs:1250
   System.Linq.<SelectIterator>d__7`2.MoveNext() +198
   System.Linq.Buffer`1..ctor(IEnumerable`1 source) +217
   System.Linq.<GetEnumerator>d__0.MoveNext() +96

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(21

太阳公公是暖光 2024-11-16 00:11:02

如果您在迭代另一个查询的结果时执行查询,则可能会发生这种情况。从您的示例中不清楚发生这种情况的位置,因为该示例不完整。

可能导致这种情况的一件事是迭代某些查询的结果时触发延迟加载。

通过在连接字符串中允许 MARS 可以轻松解决此问题。将 MultipleActiveResultSets=true 添加到连接字符串的提供程序部分(其中指定了数据源、初始目录等)。

This can happen if you execute a query while iterating over the results from another query. It is not clear from your example where this happens because the example is not complete.

One thing that can cause this is lazy loading triggered when iterating over the results of some query.

This can be easily solved by allowing MARS in your connection string. Add MultipleActiveResultSets=true to the provider part of your connection string (where Data Source, Initial Catalog, etc. are specified).

海拔太高太耀眼 2024-11-16 00:11:02

您可以在 return 语句之前使用 ToList() 方法。

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;
}

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;
}
初见你 2024-11-16 00:11:02

使用语法 .ToList() 将从数据库读取的对象转换为列表,以避免再次重新读取。

Use the syntax .ToList() to convert object read from db to list to avoid being re-read again.

败给现实 2024-11-16 00:11:02

这是一个工作连接字符串,供需要参考的人使用。

<connectionStrings>
  <add name="IdentityConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\IdentityDb.mdf;Integrated Security=True;MultipleActiveResultSets=true;" providerName="System.Data.SqlClient" />
</connectionStrings>

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>
千仐 2024-11-16 00:11:02

就我而言,使用 Include() 解决了此错误,并且根据具体情况,当可以通过连接一次查询所有查询时,比发出多个查询要高效得多。

IEnumerable<User> users = db.Users.Include("Projects.Tasks.Messages");

foreach (User user in users)
{
    Console.WriteLine(user.Name);
    foreach (Project project in user.Projects)
    {
        Console.WriteLine("\t"+project.Name);
        foreach (Task task in project.Tasks)
        {
            Console.WriteLine("\t\t" + task.Subject);
            foreach (Message message in task.Messages)
            {
                Console.WriteLine("\t\t\t" + message.Text);
            }
        }
    }
}

In my case, using Include() solved this error and depending on the situation can be a lot more efficient then issuing multiple queries when it can all be queried at once with a join.

IEnumerable<User> users = db.Users.Include("Projects.Tasks.Messages");

foreach (User user in users)
{
    Console.WriteLine(user.Name);
    foreach (Project project in user.Projects)
    {
        Console.WriteLine("\t"+project.Name);
        foreach (Task task in project.Tasks)
        {
            Console.WriteLine("\t\t" + task.Subject);
            foreach (Message message in task.Messages)
            {
                Console.WriteLine("\t\t\t" + message.Text);
            }
        }
    }
}
偏爱自由 2024-11-16 00:11:02

我不知道这是否是重复的答案。如果是的话我很抱歉。我只是想让有需要的人知道我如何使用 ToList() 解决我的问题。

就我而言,我对以下查询遇到了相同的异常。

int id = adjustmentContext.InformationRequestOrderLinks.Where(
             item => item.OrderNumber == irOrderLinkVO.OrderNumber 
                  && item.InformationRequestId == irOrderLinkVO.InformationRequestId)
             .Max(item => item.Id);

我解决如下

List<Entities.InformationRequestOrderLink> links = 
      adjustmentContext.InformationRequestOrderLinks
           .Where(item => item.OrderNumber == irOrderLinkVO.OrderNumber 
                       && item.InformationRequestId == irOrderLinkVO.InformationRequestId)
           .ToList();

int id = 0;

if (links.Any())
{
  id = links.Max(x => x.Id);
}
if (id == 0)
{
//do something here
}

I dont know whether this is duplicate answer or not. If it is I am sorry. I just want to let the needy know how I solved my issue using ToList().

In my case I got same exception for below query.

int id = adjustmentContext.InformationRequestOrderLinks.Where(
             item => item.OrderNumber == irOrderLinkVO.OrderNumber 
                  && item.InformationRequestId == irOrderLinkVO.InformationRequestId)
             .Max(item => item.Id);

I solved like below

List<Entities.InformationRequestOrderLink> links = 
      adjustmentContext.InformationRequestOrderLinks
           .Where(item => item.OrderNumber == irOrderLinkVO.OrderNumber 
                       && item.InformationRequestId == irOrderLinkVO.InformationRequestId)
           .ToList();

int id = 0;

if (links.Any())
{
  id = links.Max(x => x.Id);
}
if (id == 0)
{
//do something here
}
ぃ双果 2024-11-16 00:11:02

您似乎正在使用相同的 EF 上下文从活动查询中调用 DateLastUpdated,并且 DateLastUpdate 向数据存储本身发出命令。实体框架一次仅支持每个上下文一个活动命令。

您可以将上述两个查询重构为一个这样的查询:

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);

我还注意到您在查询中调用 FormattedAccountNumberFormattedRecordNumber 等函数。除非这些是您从数据库导入到实体数据模型中并正确映射的存储过程或函数,否则它们也会抛出异常,因为 EF 不知道如何将这些函数转换为可以发送到数据存储的语句。

另请注意,调用 AsEnumerable 不会强制执行查询。直到查询执行被推迟直到枚举出来。如果您愿意,可以使用 ToListToArray 强制枚举。

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.

ら栖息 2024-11-16 00:11:02

就我而言,我从数据上下文中打开了一个查询,例如

    Dim stores = DataContext.Stores _
        .Where(Function(d) filter.Contains(d.code)) _

...然后随后查询相同的...

    Dim stores = DataContext.Stores _
        .Where(Function(d) filter.Contains(d.code)).ToList

.ToList 添加到第一个解决了我的问题。我认为将其包装在如下属性中是有意义的:

Public ReadOnly Property Stores As List(Of Store)
    Get
        If _stores Is Nothing Then
            _stores = DataContext.Stores _
                .Where(Function(d) Filters.Contains(d.code)).ToList
        End If
        Return _stores
    End Get
End Property

其中 _stores 是私有变量,而 Filters 也是从 AppSettings 读取的只读属性。

In my case, I had opened a query from data context, like

    Dim stores = DataContext.Stores _
        .Where(Function(d) filter.Contains(d.code)) _

... and then subsequently queried the same...

    Dim stores = DataContext.Stores _
        .Where(Function(d) filter.Contains(d.code)).ToList

Adding the .ToList to the first resolved my issue. I think it makes sense to wrap this in a property like:

Public ReadOnly Property Stores As List(Of Store)
    Get
        If _stores Is Nothing Then
            _stores = DataContext.Stores _
                .Where(Function(d) Filters.Contains(d.code)).ToList
        End If
        Return _stores
    End Get
End Property

Where _stores is a private variable, and Filters is also a readonly property that reads from AppSettings.

吹泡泡o 2024-11-16 00:11:02

顺便说一句……当 SQL 对象的(内部)数据映射出现问题时,也可能会发生这种情况。

例如...

我创建了一个SQL标量函数不小心返回了一个VARCHAR...然后...用它生成了一个VIEW 中的列。 VIEW 已正确映射到 DbContext 中...因此 Linq 可以很好地调用它。但是,实体期望DateTime?,而VIEW返回字符串

哪个奇怪地抛出...

“已经有一个与此命令关联的打开的 DataReader
必须先关闭它”

很难弄清楚...但是在我更正返回参数后...一切都很好

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

云淡月浅 2024-11-16 00:11:02

发生此问题很可能是因为实体框架的“延迟加载”功能。通常,除非在初始获取期间明确要求,否则仅在需要时才获取所有联接数据(存储在其他数据库表中的任何数据)。在许多情况下,这是一件好事,因为它可以防止获取不必要的数据,从而提高查询性能(无连接)并节省带宽。

在问题中描述的情况下,执行初始获取,并且在“选择”阶段请求缺少延迟加载数据,发出附加查询,然后 EF 抱怨“打开 DataReader”。

接受的答案中提出的解决方法将允许执行这些查询,并且实际上整个请求都会成功。

但是,如果您检查发送到数据库的请求,您会注意到多个请求 - 针对每个丢失(延迟加载)数据的附加请求。这可能是性能杀手。

更好的方法是告诉 EF 在初始查询期间预加载所有需要的延迟加载数据。这可以使用“Include”语句来完成:

using System.Data.Entity;

query = query.Include(a => a.LazyLoadedProperty);

这样,将执行所有需要的联接,并且所有需要的数据将作为单个查询返回。问题中描述的问题将得到解决。

Most likely this issue happens because of "lazy loading" feature of Entity Framework. Usually, unless explicitly required during initial fetch, all joined data (anything that stored in other database tables) is fetched only when required. In many cases that is a good thing, since it prevents from fetching unnecessary data and thus improve query performance (no joins) and saves bandwidth.

In the situation described in the question, initial fetch is performed, and during "select" phase missing lazy loading data is requested, additional queries are issued and then EF is complaining about "open DataReader".

Workaround proposed in the accepted answer will allow execution of these queries, and indeed the whole request will succeed.

However, if you will examine requests sent to the database, you will notice multiple requests - additional request for each missing (lazy loaded) data. This might be a performance killer.

A better approach is to tell to EF to preload all needed lazy loaded data during the initial query. This can be done using "Include" statement:

using System.Data.Entity;

query = query.Include(a => a.LazyLoadedProperty);

This way, all needed joins will be performed and all needed data will be returned as a single query. The issue described in the question will be solved.

零崎曲识 2024-11-16 00:11:02

除了Ladislav Mrnka的回答之外:

如果您要在设置选项卡上发布和覆盖容器,则可以将MultipleActiveResultSet设置为True。您可以通过单击高级...找到此选项,它将位于高级组下。

In addition to Ladislav Mrnka's answer:

If you are publishing and overriding container on Settings tab, you can set MultipleActiveResultSet to True. You can find this option by clicking Advanced... and it's going to be under Advanced group.

剑心龙吟 2024-11-16 00:11:02

我通过改变解决了这个问题
等待 _accountSessionDataModel.SaveChangesAsync();

_accountSessionDataModel.SaveChanges();
在我的存储库课程中。

 public async Task<Session> CreateSession()
    {
        var session = new Session();

        _accountSessionDataModel.Sessions.Add(session);
        await _accountSessionDataModel.SaveChangesAsync();
     }

将其更改为:

 public Session CreateSession()
    {
        var session = new Session();

        _accountSessionDataModel.Sessions.Add(session);
        _accountSessionDataModel.SaveChanges();
     }

问题是我在创建会话(在代码中)后更新了前端中的会话,但由于 SaveChangesAsync 是异步发生的,因此获取会话会导致此错误,因为显然 SaveChangesAsync 操作尚未准备好。

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.

嘿哥们儿 2024-11-16 00:11:02

对于那些通过 Google 找到此内容的人;
我收到此错误是因为,正如错误所建议的那样,我未能在同一 SqlCommand 上创建另一个 SqlDataReader 之前关闭 SqlDataReader,错误地认为在离开创建它的方法时它将被垃圾收集。

我通过以下方式解决了该问题在创建第二个读取器之前调用 sqlDataReader.Close();。

For those finding this via Google;
I was getting this error because, as suggested by the error, I failed to close a SqlDataReader prior to creating another on the same SqlCommand, mistakenly assuming that it would be garbage collected when leaving the method it was created in.

I solved the issue by calling sqlDataReader.Close(); before creating the second reader.

用心笑 2024-11-16 00:11:02

当我循环和更新数据时,同样的错误发生在我身上
IEnumerable
当我将循环集合更改为 List 并通过 .ToList() 转换来填充它时,它解决并更新了,没有任何错误。

The same error happened to me when I was looping and updating data on
IEnumerable<MyClass>
When I changed the looped-on collection to be List<MyClass>, and filled it by converting by .ToList(), it solved and updated without any errors.

青柠芒果 2024-11-16 00:11:02

当我尝试更新读取循环中的一些记录时,我遇到了同样的错误。
我尝试了投票最多的答案 MultipleActiveResultSets=true 并发现,这只是获取下一个错误的解决方法

不允许新事务,因为有其他线程正在运行
在会话中

,适用于大型结果集的最佳方法是使用块并为每个块打开单独的上下文,如中所述。
来自实体框架的 SqlException - 新不允许事务,因为会话中还有其他线程正在运行

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

挽容 2024-11-16 00:11:02

对我来说,这是我自己的错误。当我应该使用 SqlCommand.ExecuteNonQuery() 时,我试图使用 SqlCommand.executeReader() 运行 INSERT。它被打开但从未关闭,导致了错误。请注意这种疏忽。

Well for me it was my own bug. I was trying to run an INSERT using SqlCommand.executeReader() when I should have been using SqlCommand.ExecuteNonQuery(). It was opened and never closed, causing the error. Watch out for this oversight.

烈酒灼喉 2024-11-16 00:11:02

这是从现实场景中提取的:

  • 代码在连接字符串中设置了 MultipleActiveResultSets 的阶段环境中运行良好
  • 代码发布到生产环境而没有 MultipleActiveResultSets=true
  • 如此多的页面/调用工作,而单个页面/调用失败
  • 仔细观察调用,对数据库进行了不必要的调用,需要将其删除
  • 在生产中设置 MultipleActiveResultSets=true 并发布清理后的代码,一切正常且高效

总之,不要忘记 MultipleActiveResultSets,代码可能已经运行了很长时间才发现冗余的数据库调用,这可能会非常昂贵,我建议不要完全依赖于设置 MultipleActiveResultSets 属性,但也要找出为什么代码在失败的地方需要它。

This is extracted from a real world scenario:

  • Code works well in a Stage environment with MultipleActiveResultSets is set in the connection string
  • Code published to Production environment without MultipleActiveResultSets=true
  • So many pages/calls work while a single one is failing
  • Looking closer at the call, there is an unnecessary call made to the db and needs to be removed
  • Set MultipleActiveResultSets=true in Production and publish cleaned up code, everything works well and, efficiently

In conclusion, without forgetting about MultipleActiveResultSets, the code might have run for a long time before discovering a redundant db call that could be very costly, and I suggest not to fully depend on setting the MultipleActiveResultSets attribute but also find out why the code needs it where it failed.

‖放下 2024-11-16 00:11:02

如果您使用启用了 TransactionScopeAsyncFlowOptionTransaction 范围,但忘记 await 某些存储库方法,也可能会发生这种情况。

This can also happen if you use Transaction scope with TransactionScopeAsyncFlowOption enabled, but forget to await some of the repository methods.

淡莣 2024-11-16 00:11:02

我已经通过查询进行迭代。
我通过在 @foreach 语句中放置 .ToList() 解决了我的问题。

foreach (var user in report.myUsers.ToList())
{
}

I was iterating, already through a query.
I resolved mine by placing a .ToList() in my @foreach statement.

foreach (var user in report.myUsers.ToList())
{
}
鱼窥荷 2024-11-16 00:11:02

我在我的工具中使用 Web 服务,这些服务在其中获取存储过程。当越来越多的客户端工具获取Web服务时,就会出现这个问题。我通过为那些获取存储过程的函数指定 Synchronized 属性来修复此问题。现在它工作正常,错误从未出现在我的工具中。

 [MethodImpl(MethodImplOptions.Synchronized)]
 public static List<t> MyDBFunction(string parameter1)
  {
  }

该属性允许一次处理一个请求。所以这解决了问题。

I am using web service in my tool, where those service fetch the stored procedure. while more number of client tool fetches the web service, this problem arises. I have fixed by specifying the Synchronized attribute for those function fetches the stored procedure. now it is working fine, the error never showed up in my tool.

 [MethodImpl(MethodImplOptions.Synchronized)]
 public static List<t> MyDBFunction(string parameter1)
  {
  }

This attribute allows to process one request at a time. so this solves the Issue.

失眠症患者 2024-11-16 00:11:02

就我而言,我必须在连接字符串中将 MultipleActiveResultSets 设置为 True
然后出现了另一个错误(真正的错误),即无法在同一数据上下文上同时运行 2 个(SQL)命令! (EF Core,代码优先)
因此,我的解决方案是寻找任何其他异步命令执行并将其转换为同步,因为我只有一个用于这两个命令的 DbContext。

我希望它能帮助你

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文