I’m trying to do the following transaction using Linq to sql.
but the id Field is not retrieved so an exception occurs
The INSERT statement conflicted with the FOREIGN KEY constraint
so what to do?
my code:
System.Data.Common.DbTransaction transaction = null;
DBDataContext db = new DBDataContext();
db.Connection.Open();
transaction = db.Connection.BeginTransaction();
db.Transaction = transaction;
Table1 = new Table1();
obj.objName = "some name";
db.Table1s.InsertOnSubmit(obj);
Table2 obj_info = new Table2();
obj_info.Info = "some info";
obj_info.Id = obj.Id;
db.Table2s.InsertOnSubmit(obj_info);
try
{
db.SubmitChanges();
transaction.Commit();
}
catch (Exception)
{
transaction.Rollback();
}
finally
{
transaction.Dispose();
db.Dispose();
}
Edit:maybe i the code wasn’t clear enough
the obj variable has the primary key Id so obj.Id is the auto-generated identity
and i need to insert it into obj_info.Id which is foreign key
it seems like i need to use SubmitChanges after evert insert
I’m not totally sure about this but it worked
if any one can confirm it please tell me