Note that there are some explanatory texts on larger screens.

plurals
  1. POTSQL Insert Data Linked by Foreign Key
    primarykey
    data
    text
    <p>Let's say I have two tables</p> <p><strong>RDB_DataEntities</strong></p> <pre><code>DataEntityId Name Created Modified ... </code></pre> <p><strong>RDB_DataInstances</strong></p> <pre><code>DataInstanceId DataEntityId </code></pre> <p>So <code>RDB_DataInstances</code> is joined to <code>RDB_DataEntities</code> via a foreign key on their <code>DataEntityId</code> columns.</p> <p>Let's say I want to insert data into both tables in the same transaction. The code I have for this is as follows:</p> <pre><code>using (var con = new SqlConnection("data source=speedy;initial catalog=mydb;user id=myuser;password=mypass")) { con.Open(); using (var tran = con.BeginTransaction()) { SqlCommand i1 = new SqlCommand("insert into RDB_DataEntities (Name,IsSchema,Created,Modified,RequireCaptcha,UniqueByEmail,UniqueByMac) values ('hi',0,GetDate(),GetDate(),0,0,0)", con, tran); i1.ExecuteNonQuery(); SqlCommand i2 = new SqlCommand("select SCOPE_IDENTITY() as newid", con, tran); var id = int.Parse(i2.ExecuteScalar().ToString()); SqlCommand i3 = new SqlCommand("insert into RDB_DataInstances (DataEntityId) values (" + id + ")", con, tran); i3.ExecuteScalar(); tran.Commit(); } } </code></pre> <p>Why is it throwing a foreign key error </p> <blockquote> <p>The INSERT statement conflicted with the FOREIGN KEY constraint 'FK_RDB_DataInstances_RDB_DataEntities'. The conflict occurred in database 'NMSS_CMS', table 'dbo.RDB_DataEntities', column 'DataEntityId'.</p> </blockquote> <p>Shouldn't the transaction know that I am inserting the foreign key based upon an insert I just did within the current transaction context? Am I way off?</p> <p>How do you make this happen?</p>
    singulars
    1. This table or related slice is empty.
    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.
 

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