Dmeierotto wrote:
The issue is adding an entity to a transaction collection iteratively, and the creation of unnecessary overhead.
Example Code:
Transaction transactionManager =
new Transaction(IsolationLevel.ReadCommitted, "My Trans");
try{
foreach(Entity myEntity in SomeColl){
myEntity.MyProperty = “SomeValue”;
transactionManager.Add(myEntity);
myEntity.Save();
//Could I remove the entity from the transaction here?
}
transactionManager.Commit();
catch{
transactionManager.Rollback();
}
You could also save the entities in 1 go by calling SaveMulti() of the collection. You can also add the collection to a transaction, if you want hte SaveMulti() to participate in an existing transaction:
// code using transactionManager
//...
transactionManager.Add(SomeColl);
SomeColl.SaveMulti();
This will save all entities in SomeColl in a transaction: OR a new one if the collection isn't part of an existing transaction, OR the transaction the collection was added to
1- Could I just set the transaction property of the entity object to the transaction object?
myEntity.Transaction = transactionManager;
No, use the Add() method. This makes sure the overhead required behind the scenes is been taken care of. Imagine this: You save two order entities with an identity column in a transaction. The second one fails. However the first is refetched and its ID is loaded with a value. However that's not a valid value because the transaction rolled back. So the code rolls back the internal values as well. This has to be setup first, which is done by the Transaction object's Add method.
2- Or, could I add the object to the transaction collection, execute the save, and then remove the entity from the transaction collection.
All participating objects are removed from the transaction object automatically when Rollback or Commit is called. So you don't have to do anything after the transaction object is rolled back or committed.
Option 1 or option 2 would resolve this problem if they work. Could you verify which of the options, if possible, would be best practice?
Best practise:
- when saving a collection, use the SaveMulti() methods (one of the overloads). This will create an own transaction if the collection isn't added to a transaction, otherwise it will use the transaction it's added to.
- when a save action has to be done inside a transaction, use Add() to add the object to the transaction. this can be an entity or an entitycollection
- when commit or rollback is called, entities (and collections) are automatically removed from the transaction object. The transaction object is not usable after a commit/rollback. Rollback ensures that internal datastructures inside an entity are rolled back as well.