General_9
General_9

Reputation: 2319

Retrieve Object ID after save asp.net mvc LinqToSQL

I want to retrieve the ID of the object I have just saved so I can display it to the user for future reference. Without generating the ID myself what is the best way to do this because the database auto generates the ID.

I have the following method in my repository to save to the database and I want to retrieve the ID of the saved advert immediately after:

    public void SaveNewSomeObject(SomeObject someObject)
    {
        db.SomeObjects.InsertOnSubmit(someObject);
        db.SubmitChanges();
    }

Upvotes: 1

Views: 467

Answers (1)

COLD TOLD
COLD TOLD

Reputation: 13599

you can try this retrieving the ID of the object that was inserted right after the submit changes

   db.SomeObjects.InsertOnSubmit(someObject); 
   db.SubmitChanges()
   MessageBox.Show(someObject.SomeID)

or another choice could be

var lastid = db.SomeObjects.OrderByDescending(x => x.SomeID).FirstOrDefault();
int id=lastid.SomeID;

Upvotes: 1

Related Questions