skip to Main Content

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


  1. SELECT timestamp, value, card
    FROM my_table
    ORDER BY timestamp DESC
    LIMIT 1

    Login or Signup to reply.
  2. 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 a Commit() 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.

    var course=new Course(...);
    foreach(var i=0;i<10;i++)
    {
        course.Students.Add(new Student(...));
    }
    
    context.Courses.Add(course);
    
    context.SaveChanges();
    
    Console.WriteLine($"Course ID: {course.Id}");
    foreach(var s in course.Students)
    {
        Console.WriteLine($"Student ID: {s.Id}");    
    }
    

    The DbSet.Add method add both the root course and all reachable objects to the DbContext in the Added state. All of these will be saved by SaveChanges.

    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 :

    public int BadInsert(Student student)
    {
        _context.Students.Add(student);
        _context.SaveChanges();
    }
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search