简体   繁体   中英

Multiple LINQ to SQL insert using IDENTITY from previous insert

I want to try and insert into multiple tables in my SQL Server database, however one of my first insert generates a foreign key that is IDENTITY value that I want to use it in my subsequent inserts. I am not sure how I go about with this in LINQ to SQL. I think I can do it in multiple transactions but I prefer to do this in one place ... aka within the using clause.

My pseudo code algorithm is as follow:

  1. Check if ID value exist in TABLE1.COL2 column
  2. If it does not exist then insert a new row into TABLE1
  3. Get the foreign key value of that newly inserted row from TABLE1.COL1 column.
  4. Create an object with the new foreign key value and update TABLE2.

      using (var sms = new SmsDataDataContext(connection_string) { foreach(SomeObject i in ListofObject) { TABLE1 t1 = CheckID(sms, i.ID); if (t1== null) { TABLE1 new_row = new TABLE1(); sms.TABLE1.InsertOnSubmit(new_row); //Ideally I want to do something like this even though i dont think it will work. sms.SubmitChanges(); TABLE2 update_row = new TABLE2(); update_row.ID = new_row.COL1.value; //has the newly created identity value from my last insert. //Assume this update_row exist in my TABLE2 table. sms.TABLE2.InsertOnSubmit(update_row); } } sms.SubmitChanges(); } 

LINQ to SQL was built around a unit of work pattern over an object graph rather than separate statements for each row. Assuming you have an association between your parent (Table1) and children (Table2), you should be able to build the graph up and issue a single SubmitChanges. LINQ to SQL will automatically handle setting the child's parent ID based on the value that was previously submitted.

using (var sms = new SmsDataDataContext(connection_string)
 {
    foreach(SomeObject i in ListofObject)
    {
      TABLE1 t1 = CheckID(sms, i.ID);

      if (t1== null)
      {
         TABLE1 new_row = new TABLE1();
         sms.TABLE1.InsertOnSubmit(new_row);

         TABLE2 update_row = new TABLE2();
         new_row.Table2s.Add(update_row);

      }
    }
    sms.SubmitChanges();
  }

You can use TransactionScope .

Just wrap your entire block of data-base adjustments in it like this:

using (var MyTran = new TransactionScope())
{
   try{
     //Insert #1
     //Insert #2
     ...
     MyTran.Complete();
   }catch{
     // if the flow of control comes here, transaction will not be committed
   }
}

As you can see, if your code executes before Complete() is executed, you get a rollback.

References

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM