Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I insert SQL 2008 parent and child rows in a single transaction using VB.NET?
    primarykey
    data
    text
    <p>First, a little background (greatly simplified): I have two classes, one called <em>Entity</em> and one called <em>Item</em> which a subclass of Entity. They each store their individual properties in seperate SQL 2008 tables using TableAdapters generated by a strongly typed DataSet. The Entity class has a Save() method that looks like this:</p> <pre><code>Public Sub Save() entityTableAdapter.Update(entityRow) End Sub </code></pre> <p>and the Item class has a Save method which looks like this:</p> <pre><code>Public Overrides Sub Save() MyBase.Save itemTableAdapter.Update(itemRow) End Sub </code></pre> <p>This works well except that if inserting an Item row fails then I am left with an orphaned Entity row in the database so I extended the TableAdapters and Save methods to use a transaction like so:</p> <p>Entity Save method:</p> <pre><code>Public Sub Save(tx as SqlTransaction) entityTableAdapter.Connection = tx.Connection entityTableAdapter.Transaction = tx entityTableAdapter.Update(entityRow) End Sub </code></pre> <p>Item Save method:</p> <pre><code>Public Overrides Sub Save() // setup the transaction: dim cn as SqlConnection = itemTableAdapter.Connection cn.Open dim tx as Sql Transaction = cn.BeginTransaction // save the base object properties: MyBase.Save(tx) // save this object's properties: itemTableAdapter.Connection = cn itemTableAdapter.Transaction = tx itemTableAdapter.Update(itemRow) // commit the transaction tx.Commit End Sub </code></pre> <p>Now when I attempt to save a new Item everything works up to the itemTableAdapter.Update(itemRow) where I get an error similar to </p> <blockquote> <p>INSERT statement conflicted with the FOREIGN KEY constraint... column 'EntityID'</p> </blockquote> <p>Indeed, the SQL table does not contain a row in the Entity table with the necessary ID at this point because the transaction is not complete. </p> <p>Am I going about this the wrong way? My goal is to prevent the Entity record from being inserted if inserting the Item record fails. I could write code to delete the Entity record again, but this does not seem very elegant to me...</p> <p>The code above has been greatly simplified to illustrate the problem. I am happy to post more details if it helps.</p> <p>Thanks in advance for any help!</p> <p>JE</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload