Problem with relations and System.Transactions
Posted: Mon 17 Oct 2011 16:33
I am inserting records in 2 tables so I decided to use the TransactionScope class from the System.Transactions namesape. Firstly, I wrote my code without transactions to make sure it is working. Then, I added transactions and I am having a problem. The tables have a relation which is defined using a foreign key. Insertion takes place in the parent table first, and then continues inserting several records in the child table. As soon as it tries to insert the first child record I get an exception saying that there is a foreign key violation. It seems that the parent table record is not inserted immediately when transactions are used but until transaction is completed. Is this a question for you?
Respectfully,
Jorge Maldonado
Respectfully,
Jorge Maldonado
Code: Select all
// **********************************************
// Calls insertion methods for parent and child tables.
// **********************************************
Protected void Insertion
Boolean blnError = false;
using (TransactionScope trnScope = new TransactionScope())
{
// Insertion in parent table.
ParentTable objParentTable as new ParentTable();
blnError = ParentTable.Insert();
// Insertion in child table.
if (!blnError)
{
ChildTable objChildTable = new ChildTable();
blnError = ChildTable.Insert();
}
if (!blnError)
trnScope.Complete();
}
// **********************************************
// Parent and child table methods are part of a class library.
// **********************************************
protected Boolean ParentTable()
{
// Insertion in the parent table takes place here.
// The parent table has a serial field which is the primary key.
// The insert command has a RETURNING clause to get such
// a serial field which will be used by the ChildTable method.
// I tested with and without TransactionScope here.
// If an exception is caught then TRUE is returned, else FALSE is returned.
}
protected Boolean ChildTable()
{
// Insertion in the child table takes place here.
// The primary key, which is the value of the serial field generated
// in the ParentTable() method, is used here to relate the child records
// with the parent record. It seems that the parent record is not
// inserted yet, but until the transaction is completed.
// I tested with and without TransactionScope here.
// If an exception is caught then TRUE is returned, else FALSE is returned.
}