Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 551
reid Avatar asked Oct 29 '25 20:10

reid


1 Answers

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;
like image 186
Christos Avatar answered Oct 31 '25 09:10

Christos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!