Posted by Gerhard Stephan on April 17th, 2008
The DirtyObjectException will be thrown if an object is changed by another user meanwhile the object is in use by the first user. This Optimistic Locking feature is used for objects that are derived from MarkedValueObject or MarkedAutoIncValueObject.
To evaluate the feature you can force the ObjectMapper .NET to throw a DirtyObjectException.
public void TestDirtyObjectException()
Buying buying = new Buying(5, "Hotdogs");
using (AdFactum.Data.ObjectMapper mapper = OBM.CreateMapper(Connection))
// First save
bool nested = OBM.BeginTransaction(mapper);
// Simulate, that an other user has changed the object
buying.Count = 3; // the object has to be changed
buying.LastUpdate = buying.LastUpdate.AddHours(-1);
// Second save, tend to fail
nested = OBM.BeginTransaction(mapper);
Normaly you definitly would’nt change the LastUpdate Property. That’s only for showing when the DirtyObjectException will be thrown. So let us have a look at the created SQL Statement.
UPDATE [BUYING] SET [LASTUPDATE] = CONVERT (DATETIME, '2008-04-17 20:07:46'), [COUNT] = 3
WHERE [BUYING].[ID]=1 AND [LASTUPDATE] = CONVERT (DATETIME, '2008-04-17 19:07:46');
As you can see, the WHERE Clause contains a check condition that fails, if the object has been modified meanwhile it is in use by the current user. If that happens the DirtyObjectException will be thrown to indicate that the object has been changed.