【问题标题】:Entity Framework Core: New transaction is not allowed because there are other threads running in the sessionEntity Framework Core:不允许新事务,因为会话中正在运行其他线程
【发布时间】:2019-05-06 22:31:43
【问题描述】:

我有一个具有类别层次结构的数据库。每个类别都有一个 parentcategoryid。我调用以下函数来加载顶级类别,然后递归调用自身来加载所有子类别。

但是,我收到以下错误:

SqlException: 不允许新事务,因为还有其他 会话中运行的线程。

    public async Task LoadCategoriesAsync()
    {
        await LoadCategoriesByParentId(null);
    }

    private async Task LoadCategoriesByParentId(int? sourceParentId, int? parentId)
    {
        var sourceCategories = _dbContext.SourceCategory.Where(c => c.ParentCategoryId == sourceParentId);
        foreach (var sourceCategory in sourceCategories)
        {
            var newCategory = new Category()
            {
                Name = sourceCategory.Name,
                Description = sourceCategory.Description,
                ParentCategoryId = parentId
            };

            _dbContext.Category.Add(newCategory);
            await _dbContext.SaveChangesAsync();

            //category.EntityId = newCategory.Id;
            //_dbContext.SourceCategory.Update(category);
            //await _dbContext.SaveChangesAsync();

            await LoadCategoriesByParentId(sourceCategory.CategoryId, newCategory.Id);
        }
    }

【问题讨论】:

    标签: asp.net-core entity-framework-core


    【解决方案1】:

    您的Where() 语句未检索数据;只是“打开光标”(用老话说)。所以,你不能做SaveChange()。最简单的解决方案是将IEnumerable 转换为ListArray

    var rootCategories = _dbContext.SourceCategory.Where(c => c.ParentCategoryId == parentId).ToList();
    

    但我强烈建议您在 Google 上搜索该错误并了解它发生的原因。递归地这样做是乞求麻烦

    【讨论】:

    • 谢谢。 ToList() 有效,但我明白你的意思。如果我在每次调用我的方法时都设置断点并停止,我会得到所有数据,但如果我让它在没有断点的情况下运行,我只会得到部分数据。但是,我看不到任何其他方法可以做我想做的事情。因为它是一个层次结构,我需要知道我插入的每个项目的 parentID,我需要从顶部开始,然后递归地向下工作。您知道我可以尝试的其他方法吗?
    • 对于初学者来说,不清楚你想要做什么。您不分配类别;所以他们在通话结束时会丢失。
    • 我在上面的代码中有一个错误,传递了错误的 ParentId。我只是更改了上面的代码。当我现在添加 ToList() 时它似乎可以工作,但速度很慢。我有一个具有类别层次结构的表,我将它们插入到另一个表中。
    猜你喜欢
    • 1970-01-01
    • 2016-07-07
    • 2017-03-27
    • 2018-05-20
    • 1970-01-01
    • 2012-09-07
    • 2021-08-20
    • 2012-04-23
    • 2017-06-26
    相关资源
    最近更新 更多