简体   繁体   English

ASP-Net Core Sql命令并发问题

[英]ASP-Net Core Sql command concurrency issue

The back end of my application runs on NetCore as a Web API. 我的应用程序后端在NetCore上作为Web API运行。 The front end can be considered unrelated. 前端可以认为是无关的。

Most of my application runs on Entity framework. 我的大部分应用程序都在Entity框架上运行。 However I've recently had to implement some custom filtering into one of our DB calls. 但是,最近我不得不在我们的一个数据库调用中实现一些自定义过滤。 This Db call is called up to 3 times at once when a page on the web UI is loaded. 加载Web UI上的页面时,一次最多调用3次Db呼叫。

I'm having issues with the following code, which is throwing the following error: System.InvalidOperationException: 'The connection was not closed. The connection's current state is open.' 我遇到以下代码的问题,该代码引发以下错误: System.InvalidOperationException: 'The connection was not closed. The connection's current state is open.' System.InvalidOperationException: 'The connection was not closed. The connection's current state is open.'

The code: 编码:

foreach (var filter in dbFilters)
{

    var cacheKey = $"matching_filters_id:{matchingConfigId}_filter:{filter.FilterFunctionName}";
    var ids = new List<int>();

    if (!_cache.TryGetValue(cacheKey, out ids))
    {
        ids = new List<int>();
        using (var conn = _dbContext.Database.GetDbConnection())
        {
            conn.Open();
            using (var command = conn.CreateCommand())
            {
                command.CommandText =
                    SqlHelper.BuildGetMatchingFilterIdsForIntersect(filter.FilterFunctionName);
                using (var result = command.ExecuteReader())
                {
                    while (!result.IsClosed && result.Read())
                    {
                        ids.Add((int) result["ItemId"]);
                    }
                }
            }
            conn.Close();
        }

        var cacheEntryOptions = new MemoryCacheEntryOptions()
            .SetSlidingExpiration(TimeSpan.FromSeconds(30));
        _cache.Set(cacheKey, ids, cacheEntryOptions);
    }

    // Joins filtered list against each filter to make the list smaller.
    firstFilter = firstFilter.Join(ids, o => o.SourceKey, id => id, (o, id) => o).ToArray();
}

What i'm attempting to do, is filter the list firstFilter which is a POCO containing a few properties. 我正在尝试做的是过滤列表firstFilter ,这是一个包含一些属性的POCO。 I'm attempting to filter this by joining it to one or more list of filtered ItemIds being returned from multiple different SQL queries. 我正在尝试通过将其加入从多个不同的SQL查询返回的一个或多个已过滤ItemId列表来对此进行过滤。 Not the most elegant solution but its what i have to work with. 不是最优雅的解决方案,而是我必须使用的解决方案。

What i understand to be happening is that as the client is calling this method more then once, the methods are executing concurrently, causing the DB connection to be opened twice at once, causing the connection to fail and the error to be thrown. 我了解正在发生的事情是,随着客户端调用此方法的次数超过一次,这些方法同时执行,从而导致DB连接一次打开两次,从而导致连接失败并引发错误。

I've attempted to stop this from happening by removing the async keyword form my method: public JsonResult GetMatches(int matchingConfigId...... ) but without success. 我试图通过从我的方法中删除async关键字来阻止这种情况的发生: public JsonResult GetMatches(int matchingConfigId...... )但没有成功。 I've also tried to intorduce session into the application, which I've read might cause calls to the same method from one client 'session' to happen in sequence rather then concurrently. 我还尝试将会话引入到应用程序中,我已阅读该会话可能导致从一个客户端“会话”对同一方法的调用依次发生,而不是同时发生。 But this has not seemed to have any effect. 但这似乎没有任何效果。

Of course i might be barking up the entirely wrong tree.. but I've been bashing my head against said tree for most of the day now and I've reached my limit. 当然,我可能正在吠叫完全错误的树..但是,现在大部分时间我一直在对着那棵树猛击头,我已经达到了极限。 Any help would be greatly appreciated 任何帮助将不胜感激

因此,事实证明来自实体框架的变量dbFilters尚未使用ToList()ToListAsync()进行解析,因此该调用与数据库的连接仍处于打开状态,从而导致上述调用一段代码失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM