Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DbContext SaveChanges Order of Statement Execution

I have a table that has a unique index on a table with an Ordinal column. So for example the table will have the following columns:

TableId, ID1, ID2, Ordinal

The unique index is across the columns ID1, ID2, Ordinal.

The problem I have is that when deleting a record from the database I then resequence the ordinals so that they are sequential again. My delete function will look like this:

    public void Delete(int id)
    {
        var tableObject = Context.TableObject.Find(id);
        Context.TableObject.Remove(tableObject);
        ResequenceOrdinalsAfterDelete(tableObject);
    }

The issue is that when I call Context.SaveChanges() it breaks the unique index as it seems to execute the statements in a different order than they were passed. For example the following happens:

  1. Resequence the Ordinals
  2. Delete the record

Instead of:

  1. Delete the record
  2. Resequence the Ordinals

Is this the correct behaviour of EF? And if it is, is there a way of overriding this behaviour to force the order of execution?

If I haven't explained this properly, please let me know...

like image 220
didiHamman Avatar asked Sep 07 '11 14:09

didiHamman


People also ask

What does the DbContext SaveChanges () method return?

Returns. The number of state entries written to the underlying database.

Does SaveChanges commit transaction?

Yes, if you explicitly wrap your context within a transaction such as . Net's TransactionScope, you can retrieve auto-generated IDs from entities after a . SaveChanges() call, without committing the scoped transaction.

When should you call context SaveChanges?

If you need to enter all rows in one transaction, call it after all of AddToClassName class. If rows can be entered independently, save changes after every row.


1 Answers

Order of commands is completely under control of EF. The only way how you can affect the order is using separate SaveChanges for every operation:

public void Delete(int id)
{
    var tableObject = Context.TableObject.Find(id);
    Context.TableObject.Remove(tableObject);
    Context.SaveChanges();
    ResequenceOrdinalsAfterDelete(tableObject);
    Context.SaveChanges();
}

You should also run that code in manually created transaction to ensure atomicity (=> TransactionScope).

But the best solution would probably be using stored procedure because your resequencing have to pull all affected records from the database to your application, change their ordinal and save them back to the database one by one.

Btw. doing this with database smells. What is the problem with having a gap in your "ordinal" sequence?

like image 91
Ladislav Mrnka Avatar answered Oct 28 '22 23:10

Ladislav Mrnka