sarneeh
sarneeh

Reputation: 1388

Calling multiple SaveChanges()

I'm trying to work asynchronously on one database table and commit changes to it but it doesn't work as I would like it to.

This is my first method where I'm running a task on object constructor which is non-busy waiting for some new objects in the collection and processing them one by one. (Deleting from the 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();
                }
            }
        });
    }

And here's the second method which is providing the objects to the database. (Adding to the table)

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

            scope.Complete();
        }

Both methods are using the same UnitOfWork object with needed repositories.

After I run the app and while the queue task is running - when I'm sending new objects to the second method, I'm getting the error below:

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.

The question is: how to get rid of this exception? Or how can I do it in some other way? I've tried already the new EF 6.0 BeginTransaction method but it also didn't work for me (or maybe i used them wrong).

Upvotes: 0

Views: 1449

Answers (1)

wvisaacs
wvisaacs

Reputation: 188

You shouldn't be sharing your context objects across multiple threads. The error message you posted is essentially stating that the context object realizes entities have been modified.

Try using a separate context object for each thread: Entity Framework Thread Safety

Upvotes: 2

Related Questions