views:

426

answers:

2

Could any of you please show me how to complete the following tasks?

// Prepare object to be saved
// Note that MasterTable has MasterTableId as a Primary Key and it is an indentity column

MasterTable masterTable = new MasterTable();
masterTable.Column1 = "Column 1 Value";
masterTable.Column2 = 111;

// Instantiate DataContext
DataContext myDataContext = new DataContext("<<ConnectionStrin>>");

// Save the record
myDataContext.MasterTables.InsertOnSubmit(masterTable);
myDataContext.SubmitChanges();

// ?QUESTION?
// Now I need to retrieve the value of MasterTableId for the record just inserted above.

Kind Regards

+4  A: 

The identity value is assigned to the inserted object just after you call SubmitChanges.

Just access:

masterTable.MasterTableId
CMS
A: 

I know that LINQ to SQL automatically wraps all changes in a database transaction. So if I wanted to use the returned ID for another insert (my user table has an AddressID, so I add a new Address record and then add a new user record with that ID) and there was a problem inserting a user, the address insert would not roll back. Should you wrap both SubmitChanges in another transaction?