0

我正在尝试根据用户提供的一些规范实现批量插入和删除操作IList<Specification>。需要查询的数据大约是 100 万,据此我需要在另一个表中插入或删除记录,即UserSpecifications只有两列的表UserIdSpecificationId并且 PK 是UserId + SpecificationId

记录插入/删除到表中的顺序UserSpecifications无关紧要

因此,我正在尝试为每个用户规范创建并行任务并将数据处理到 UserSpecifications

    await Task.Run(() => Parallel.ForEach(specifications, async specification =>
    {
        await insertBulkRecordsAsync(specification); // this uses SqlBulkCopy for data insertion with transaction scope , on 1 million records
        await deleteRecordsAsync(specification); // this uses https://entityframework-plus.net/batch-delete operation
    }));

insertBulkRecordsAsync&deleteRecordsAsync使用 userContext

当我尝试运行这段代码时,出现以下异常

The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread-safe.

我知道 EF 6 不支持共享 dbContext,但是如果我运行正常的 forEach 循环,事情确实可以工作,但处理更新需要很多时间

以下作品没有任何问题

foreach (var specification in specifications)
{
  await insertBulkRecordsAsync(specification);
  await deleteRecordsAsync(specification);
}

那么我们有什么方法可以共享上下文并增加执行时间

4

0 回答 0