views:

72

answers:

4

I suppose the question was asked before (it's so general) but I can't find the answer.

How can I retrieve auto generated integer primary key value after I inserted a new row and called "SubmitChanges" ? I need to know the key exactly on the client-side 'cos I'm going to use this value further for calculations.

When unique key is Guid I can generate primary key value on the client-side. But what about generated values on the server-side?

Thank you in advance!

+2  A: 

Linq-to-SQL retrieves them back when you submit, so you can just check the value on the object you just inserted.

E.g.:

Employee emp = new Employee { FirstName = "John", LastName="Doe" };
dc.Employees.InsertOnSubmit(emp);
dc.SubmitChanges();

int employeeID = emp.ID;
KristoferA - Huagati.com
+1  A: 

It should be populated in your object once the submit has completed. This applies to the generation of int as well as rowguid.

Lazarus
+1  A: 

See this SO question.

Andy Robinson
+3  A: 

After SubmitChanges, You have primary key updated in your entity.

ex:

db.Product.InsertOnSubmit(product);
db.SubmitChanges();

product.Id // now you have updated PK/autogenerated value
Krunal