调用多个 SaveChanges()

Calling multiple SaveChanges()

我正在尝试在一个数据库上异步工作 table 并提交更改,但它没有像我希望的那样工作。

这是我的第一种方法,我在其中 运行 在对象构造函数上执行任务,该任务不忙于等待集合中的一些新对象并逐个处理它们。 (从 table 中删除)

    private static BlockingCollection<QueuedLog> queue = new BlockingCollection<QueuedLog>();

    private void Start()
    {
        Task.Run(() =>
        {
            while (taskQueueActive)
            {
                using (var scope = new TransactionScope())
                {
                    QueuedLog log = queueLogs.Take();

                    // I process it somehow here

                    uow.QueuedLogRepository.Delete(log);

                    if (queueLogs.Count == 0)
                        uow.Save();

                    scope.Complete();
                }
            }
        });
    }

这是向数据库提供对象的第二种方法。 (添加到table)

        using (var scope = new TransactionScope())
        {
            uow.MonitoringIdRepository.Add(logs.First(), out id);
            uow.QueuedLogRepository.Add(logs, id);
            uow.Save();

            scope.Complete();
        }

两种方法都使用具有所需存储库的相同 UnitOfWork 对象。

在我 运行 应用程序和队列任务 运行ning 之后 - 当我将新对象发送到第二种方法时,我收到以下错误:

An exception of type 'System.Data.Entity.Infrastructure.DbUpdateConcurrencyException' occurred in EntityFramework.dll but was not handled in user code. Additional information: Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.

问题是:如何摆脱这个异常?或者我怎样才能以其他方式做到这一点?我已经尝试过新的 EF 6.0 BeginTransaction 方法,但它对我也不起作用(或者我用错了)。

您不应该跨多个线程共享您的上下文对象。您发布的错误消息本质上是在说明上下文对象实现实体已被修改。

尝试为每个线程使用单独的上下文对象:Entity Framework Thread Safety