Students table has id ,name , gender,address columns. id is the identity column. when each student details added to this table using below lines of code,
_dataContext.Students.Add(student);
_dataContext.SaveChanges();
I need to get last inserted id value. this id value I need to insert to other table say ‘Subject’ table as studentid column.
How can I get last inserted id ?
2
Answers
SELECT timestamp, value, card
FROM my_table
ORDER BY timestamp DESC
LIMIT 1
You already the
Id
.SaveChanges
takes care of retrieving the IDs and fixing up relations for all the objects it persists.A DbContext detects all modifications to the objects it tracks and persists all of them in a single transaction when
SaveChanges
is called.SaveChanges
is essentially aCommit()
call and should only be called at the very end of a unit of work/business transaction.SaveChanges
will save all changes for all new or modified objects, retrieve the new IDs for the new objects and fix up relations. After it,student.Id
should have the new value, along with any other new class related to it.This means you could write the following code to persist a new course and students, and get back the IDs for all of them.
The
DbSet.Add
method add both the root course and all reachable objects to the DbContext in theAdded
state. All of these will be saved bySaveChanges
.If you want to discard the changes, just don’t call
SaveChanges
. When the DbContext gets disposed, the changes will be lost too.That explains why all the non-"repository" CRUD classes are so badly broken. A method like this :
Has no way of rolling back the possibly dozens of DELETEs, UPDATE and INSERTs it may execute beyond the single Student. You’d have to explicitly open a connection and start a long-running transaction to be able to roll back that Student if something goes wrong.