tags:

views:

115

answers:

2

Lets say I have a table with RowId, and Value:

1 valueA
2 valueB
3 valueC
4 valueD

Then let's say I delete the 4th row:

1 valueA
2 valueB
3 valueC

So the next row ID will be 5. Because the 4th row was deleted, I can't simply find the last row in the table and add 1 to get the next row ID. How can I obtain the next row ID?

Thanks!

+2  A: 

After you insert a new row you will get the row ID. I don't see why you would need it before you insert it!

tster
+2  A: 

In LinqToSQL, if two classes each have a PRIMARY KEY IDENTITY columns and have a connecting association (created by FKey in the database or manually in the designer), you can do your two related items insert like this:

Customer c = new Customer() {Name = "Bob"};
Order o = new Order() {Customer = c, Quantity = 5};

myDataContext.InsertOnSubmit(c);
  //submit changes will insert c and o
  //  in the right order and with all id's populated.
myDataContext.SubmitChanges();
  //the id's are populated 
int customerID = c.CustomerID;
int orderID = o.OrderID;
customerID = o.CustomerID;
David B
+1 exactly - let Linq-to-SQL handle all those messy details and don't worry about guessing ID's ahead of time!
marc_s
I think you'd have to InsertOnSubmit(o) if you want both objects inserted. c doesn't reference o. Right?
uosɐſ
c references o through an Orders property created by the association. This same association created the Order.Customer property.
David B