Can I return the 'id' field after a LINQ insert?

naspinski picture naspinski · Sep 22, 2008 · Viewed 101.9k times · Source

When I enter an object into the DB with Linq-to-SQL can I get the id that I just inserted without making another db call? I am assuming this is pretty easy, I just don't know how.

Answer

Germstorm picture Germstorm · Sep 22, 2008

After you commit your object into the db the object receives a value in its ID field.

So:

myObject.Field1 = "value";

// Db is the datacontext
db.MyObjects.InsertOnSubmit(myObject);
db.SubmitChanges();

// You can retrieve the id from the object
int id = myObject.ID;