Tuesday, 15 May 2012

c# - Multiple LINQ to SQL insert using IDENTITY from previous insert -



c# - Multiple LINQ to SQL insert using IDENTITY from previous insert -

i want seek , insert multiple tables in sql server database, 1 of first insert generates foreign key identity value want utilize in subsequent inserts. not sure how go in linq sql. think can in multiple transactions prefer in 1 place ... aka within using clause.

my pseudo code algorithm follow:

check if id value exist in table1.col2 column if not exist insert new row table1 get foreign key value of newly inserted row table1.col1 column.

create object new foreign key value , update table2.

using (var sms = new smsdatadatacontext(connection_string) { foreach(someobject in listofobject) { table1 t1 = checkid(sms, i.id); if (t1== null) { table1 new_row = new table1(); sms.table1.insertonsubmit(new_row); //ideally want though dont think work. sms.submitchanges(); table2 update_row = new table2(); update_row.id = new_row.col1.value; //has newly created identity value lastly insert. //assume update_row exist in table2 table. sms.table2.insertonsubmit(update_row); } } sms.submitchanges(); }

linq sql built around unit of work pattern on object graph rather separate statements each row. assuming have association between parent (table1) , children (table2), should able build graph , issue single submitchanges. linq sql automatically handle setting child's parent id based on value submitted.

using (var sms = new smsdatadatacontext(connection_string) { foreach(someobject 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(); }

c# sql-server linq

No comments:

Post a Comment