Search code examples
c#linqasp.net-mvc-4

How to get the last insert ID in LINQ


I have two tables, user and student. user is the parent table and student is the child table

so from the following code

public void adduserStudenttype(StudentAddUserModel s)
{
    using (DASEntities db = new DASEntities())
    {
        user u = new user();
        u.usersEmail = s.Email;
        u.usersPassword = s.Password;
        u.usersFname = s.Fname;
        u.usersUtype = s.UserType;
        db.user.Add(u);
        db.SaveChanges();
        
        student stud = new student();
        stud.studentID = \\ how to get the id in the user last insert
    }     
}

how can i get the last insert id from the user table? id is the primary key in user table.


Solution

  • You could get it as below:

    // I suppose that the corresponding's property name is ID.
    // If it is not, you should change it correspondingly.
    stud.studentID = u.ID;