views:

1144

answers:

4

Hi everyone,

How can I get a record id after saving it into database. Which I mean is actually something like that.

I have Document class (which is entity tho from DataBase) and I create an instance like

Document doc = new Document() {title="Math",name="Important"};
dataContext.Documents.InsertOnSubmit(doc);
dataContext.SubmitChanges();

than what I want is to retrieve it's id value (docId) which is located in database and it's primary key also automatic number. One thing, there will be lots of users on the system and submits tons of records like that.

Thanks in advance everybody :)

+7  A: 

Once you have run .SubmitChanges then doc.docId should be populated with the Id that was created on the database.

ChrisHDog
+1  A: 

Linq to SQL does change tracking by default. So once your row is inserted, your object is updated and added to the datacontext. You will have a new valid row in your documents collection.

This blog post by Charlie Calvert has some good Linq samples for download. I keep it just for reference.

Perpetualcoder
+2  A: 

Like everyone has said you should be able to do something like this:

Document doc = new Document() {title="Math",name="Important"};
dataContext.Documents.InsertOnSubmit(doc);
dataContext.SubmitChanges();

then get the Id with:

int ID = doc.docId;
Nathan W
Thanks for helping and revising the code.
Braveyard
A: 

Fantastic. Thank you.

Jimmy