title: Trying to create foreign keys and insert their values in a .mdb database using C# and OleDb
body: <p>I have a database with 3 tables. One of them holds a relation of the other two. E.g.:</p>
  
  <pre><code>Table1 = idTable1 (PK_Table1), attribute1, attribute2, attribute3
  
  Table2 = idTable2 (PK_Table2), attribute1
  
  Table3 = idTable3 (PK_Table3), attribute1 (FK relating to idTable1), attribute2 (FK relating to idTable2)
  </code></pre>
  
  <p>All primary keys are auto-incrementing fields assigned automatically by Access (2002 version, that's why my db is a .mdb).</p>
  
  <p>In my code I insert data in Table1 and Table2 using some code like this:</p>
  
  <pre><code>public void insert()
  {
      string query = "INSERT INTO Table1 (attribute1,attribute2,attribute3) VALUES (?,?,?)";
      OleDbConnection dbConnection = new OleDbConnection();
      dbConnection.ConnectionString = connStr;
      try
      {
          dbConnection.Open();
          OleDbCommand commandStatement = new OleDbCommand();
          OleDbCommand primarykey = new OleDbCommand("ALTER TABLE Table1 ADD CONSTRAINT pk_Table1 primary key(idTable1)", dbConnection);
          primarykey.Connection = dbConnection;
  
          commandStatement.Connection = dbConnection;
          commandStatement.CommandText = query;
          commandStatement.Parameters.Add("attribute1", OleDbType.Integer).Value = attribute1;                
                  commandStatement.Parameters.Add("attribute2", OleDbType.Integer).Value = attribute2;
          commandStatement.Parameters.Add("attribute3", OleDbType.Integer).Value = attribute3;
  
          commandStatement.ExecuteNonQuery();
          primarykey.ExecuteNonQuery(); 
          dbConnection.Close();
          dbConnection.Dispose();
          commandStatement.Dispose();
                  primarykey.Dispose();
      }
      catch (Exception e)
      {
          Console.WriteLine(e.Message);
      }
  }
  </code></pre>
  
  <p>(and then something like that for Table2 as well).</p>
  
  <p>For each row in Table1, I insert about 40 rows in Table2 (they're tables holding info of a contest and their contestants).</p>
  
  <p>Now I need to create a relation between those two, using Table3, which must reference the id of both tables as foreign keys.</p>
  
  <p>And that's where I'm lost. I don't know how to say "take the id of the row you just inserted in Table1 and then the id of a row you just inserted in Table2 and insert them as a new record in Table3".</p>
  
  <p>Is there a way to get the autoincrementing IDs that are being assigned by the database, as soon as I insert a record?</p>