I have the following (in semi-pseudo code)
It inserts a new Parent record, gets the new id of this record, and then inserts the child record (which has a foreign key on the id of the parent)
I get a foreign key error when running this code ("The INSERT statement conflicted with the FOREIGN KEY constraint...")
I thought that so long as I wrapped the queries within a transaction, that the insert of the child record would know that the Parent table contains a record with an id of value newid, even though the first insert hasn't been yet committed
Is it not possible to do such an insert like this, or am I fundamentally wrong somewhere?
Many thanks for any pointers
~LFCfan
Code:
using (SqlTransaction transaction = connection.BeginTransaction())
{
try
{
int newid = InsertParent(transaction, ...);
InsertChild(newid, transaction, ...);
transaction.Commit();
}
catch (System.Data.SqlClient.SqlException exp)
{
transaction.Rollback();
throw exp;
}
finally
{
transaction.Dispose();
}
I get a foreign key error when running this code ("The INSERT statement conflicted with the FOREIGN KEY constraint...")
I thought that so long as I wrapped the queries within a transaction, that the insert of the child record would know that the Parent table contains a record with an id of value newid, even though the first insert hasn't been yet committed
Is it not possible to do such an insert like this, or am I fundamentally wrong somewhere?
Many thanks for any pointers
~LFCfan