DBConcurrency exception using Entity Framework 6

I get an error while completing a task that should be fairly simple.

I use Entity Framework 6 code first.

I add a new object to my context, deleting it, and then save. This throws a DBConcurrency exception (I'm the only user).

To do this, I do the following:

zurich.TagProjectGroupItems.Add (tagProjectGroupItem); zurich.TagProjectGroupItems.RemoveRange (items);

(originally added item was part of the collection)

int counter = zurich.SaveChanges ();

This throws the following exception:

An exception of the type "System.Data.Entity.Infrastructure.DbUpdateConcurrencyException" occurred in EntityFramework.dll, but was not processed in the user code Additional information: an expression about saving, inserting or deleting affected an unexpected number of lines (0). Objects can be modified or deleted as objects are loaded. Update ObjectStateManager Records.

Objectcontext tells me that I have 0 new entries, 0 updated and 1 to delete. I would suggest that it tries to remove the object from the database and return 0 results, because the object was not written.

Am I doing something incredibly wrong ?! I had never used the first code before and used the model first in EF4 first. I'm at a dead end.

Thank you very much,

Rob

+6
source share
1 answer

DbUpdateConcurrencyException is called "when it was expected that SaveChanges for an object would update the database, but in fact there were no rows in the database." A source

I think EntityFramework does this check to prevent concurrency problems in multi-user scripts.

You can insert another zurich.SaveChanges(); immediately after adding the item, and then it should successfully remove the items, but as you mentioned, this is not ideal.

Perhaps you should check the collection of elements instead - and if tagProjectGroupItem is contained within the elements, then do not call zurich.TagProjectGroupItems.Add(tagProjectGroupItem); instead, remove tagProjectGroupItem from the collection before invoking the database operation.

0
source

Source: https://habr.com/ru/post/958518/


All Articles