One of the more significant services the DataContext provides is change tracking for entity objects. When
you insert, change, or delete an entity object, the DataContext is monitoring what is happening.
However, no changes are actively being propagated to the database. The changes are cached by the
DataContext until you call the SubmitChanges method.
When you call the SubmitChanges method, the DataContext object’s change processor manages
the update of the database.
First, the change processor will insert any newly inserted entity objects
to its list of tracked entity objects.
Next, it will order all changed entity objects based on their dependencies
resulting from foreign keys and unique constraints.
Then, if no transaction is in scope, it will
create a transaction so that all SQL commands carried out during this invocation of the SubmitChanges
method will have transactional integrity. It uses SQL Server’s default isolation level of ReadCommitted,
which means that the data read will not be physically corrupted and only committed data will be
read, but since the lock is shared, nothing prevents the data from being changed before the end of
the transaction.
Last, it enumerates through the ordered list of changed entity objects, creates the
necessary SQL statements, and executes them.
If any errors occur while enumerating the changed entity objects,
if the SubmitChanges method
is using a ConflictMode of FailOnFirstConflict, the enumeration process aborts, and the transaction
is rolled back, undoing all changes to the database, and an exception is thrown.
If a ConflictMode
of ContinueOnConflict is specified, all changed entity objects will be enumerated and processed
despite any conflicts that occur, while the DataContext builds a list of the conflicts. But again, the
transaction is rolled back, undoing all changes to the database, and an exception is thrown. However,
while the changes have not persisted to the database, all of the entity objects’ changes still exist in the
entity objects. This gives the developer the opportunity to try to resolve the problem and to call the
SubmitChanges method again.
If all the changes are made to the database successfully, the transaction is committed, and the
change tracking information for the changed entity objects is deleted, so that change tracking can
restart fresh.