Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Get ID of last added record

Tags:

asp.net-mvc

I'm using an MVC webform to insert a record into a database with several subrecords. In my code-behind I'm first creating a new main record using dataRepository.Add(xx). Now I need to add 5 subrecords that need the ID of the newly created record. How can I retrieve that?

like image 532
Erwin1441 Avatar asked Sep 08 '10 12:09

Erwin1441


1 Answers

Assuming xx is your model, and its primary key is Id you can get the Id of your inserted record like this:

// at this point xx.Id == null
db.XX.AddObject(xx);
db.SaveChanges();
// now: xx.Id > 0
int id = xx.Id;
like image 155
Frank van Eykelen Avatar answered Oct 21 '22 11:10

Frank van Eykelen