Use transaction from a sub function
By Adam Nagy
If you start a transaction inside your main function, then you do not need to create another one (a sub transaction) inside your sub function, you do not even need to pass the transaction to the sub function, you can simply use ObjectId.GetObject() instead, which will automatically use the outer transaction you started.
< .. code follows .. >
Most of the code I've written in recent years assumes there's an active transaction,
and uses ObjectId.GetObject(), or some extension methods I use that gets the top
transaction for adding new objects, etc. If I need to pass something, it's usually a
Database, since I can get the top/active transaction from it. A transaction has no
Database property, so if I need the Database, passing a transaction isn't terribly
useful.
public static class BlockTableRecordExtensions
{
// Append a sequence of new entities to the block
// and add to the top transaction. If an error is
// raised, all entities in the sequence will be
// disposed.
public static ObjectIdCollection Add( this BlockTableRecord owner, IEnumerable<Entity> entities )
{
if( entities == null )
throw new ArgumentNUllException
( "entities" ); Transaction trans = owner.Database.TransactionManager.TopTransaction;
if( tr == null )
throw new Autodesk
.AutoCAD.Runtime.Exception( ErrorStatus
.NoTransaction ); ObjectIdCollection ids
= new ObjectIdCollection
(); try
{
foreach( Entity ent in entities )
{
ids.Add( owner.AppendEntity( ent ) );
trans.AddNewlyCreatedDBObject( ent, true );
}
}
catch
{
entities.DisposeAll();
throw;
}
return ids;
}
// Allows entities to be passed as parameters to the above method:
public static ObjectIdCollection AddRange( this BlockTableRecord owner, params Entity[] entities )
{
return Add( owner, (IEnumerable<Entity>) entities );
}
// Append a single entity and add to top transaction.
public static ObjectId Add( this BlockTableRecord owner, Entity ent )
{
if( owner == null )
throw new ArgumentNullException
( "owner" ); if( ent == null )
throw new ArgumentNullException
( "ent" ); try
{
ObjectId id = owner.AppendEntity( ent );
owner.Database.TransactionManager.AddNewlyCreatedDBObject( ent, true );
return id;
}
catch
{
ent.Dispose();
throw;
}
}
public static void DisposeAll( this IEnumerable<IDisposable> disposables )
{
foreach( IDisposable disposable in disposables )
disposable.Dispose();
}
}