Reputation: 81711
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 :)
Upvotes: 8
Views: 7911
Reputation: 55472
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;
Upvotes: 5
Reputation: 13571
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.
Upvotes: 2
Reputation: 4663
Once you have run .SubmitChanges then doc.docId should be populated with the Id that was created on the database.
Upvotes: 12