实体框架核心:不允许新事务,因为会话中还有其他线程



我有一个具有类别层次结构的数据库。每个类别都有一个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);
        }
    }

您的Where()语句不会检索数据;只需"打开光标"(以旧服务为单位(。因此,您不能进行SaveChange()。最简单的解决方案是将IEnumerable转换为ListArray

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

,但我强烈建议您使用Google错误,并了解为什么会发生错误。递归进行此操作是乞讨 atrouty

相关内容

最新更新