Click here to Skip to main content
15,355,608 members
Please Sign up or sign in to vote.
3.50/5 (2 votes)
See more:
I am trying to insert value in two table OrderDetails And CustOrder using transaction but it gives me error: You cannot add or change a record because a related record is required in table.
Code :
C#
private void FunInsOrderDetails()
        {
         using (OleDbConnection connection = new OleDbConnection(DataConnection.constring))
         {
          OleDbTransaction transaction = null;
           try
            {
              OleDbCommand command = connection.CreateCommand();                  
              connection.Open();
              transaction = connection.BeginTransaction(); // Assign Transaction to Command
              command.Transaction = transaction;
command.CommandText= "insert into Custorder values('" + cmbOrderType.Text + "'," + txtOrderNo.Text + ",'" + dtpDate.Value.ToString("yyyy-MM-dd") + "','" + txtYourOrderNo.Text + "'," + cmbCustName.SelectedValue.ToString() + ")";                  
                   command.ExecuteNonQuery();                   
                    FunInsOrder(command);
                    transaction.Commit();
                    connection.Close();
                }
                catch
                {
                    transaction.Rollback();
                    connection.Close();
                    throw;
                }
            }           
        }


After inserting into the first table try to fetch OrderId from Custorder table
using Query:
C#
str="Select OrderId from Custorder where OrderNo="+txtOrderNo.Text+" AND OrderType='"+cmbOrderType.Text+"'";
              int OrderId = dc.RetutnID(str);

i want to insert OrderId value in OrderDetails table but it gives me a error:
You cannot add or change a record because a related record is required in table
Posted
Updated 23-Apr-14 18:23pm
v5
Comments
Sunasara Imdadhusen 22-Apr-14 7:19am
   
Please share structure of both tables.
Brahmmam 23-Apr-14 6:06am
   
is there any foreign key relation for those tables?
NABIN SEN 24-Apr-14 0:29am
   
OrderId is primary key in Custorder table and foreign key in OrderDetails table
Brahmmam 24-Apr-14 0:54am
   
you cannot change values other than OrderId column values in Custorder table because OrderDetails table's Foreighn key is assosiated with primary key in Custorder table.
NABIN SEN 25-Apr-14 0:04am
   
i am not changing OrderId columns in Custorder table.

1 solution

It is may be data you are entering is not saving in the database, due to some error at sql side it may be rolled back . and in next step you are fetching the order id key.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900