ary
ary

Reputation: 959

asp.net mvc 5 create new rows in detail table at same time as master table

So I am using asp.net mvc5 . I used database first approach to create simple web application. My question is how can I create child record when parent record is created. Let's say I have 3 tables that is (1)Students (2)Subject and (3)StudentSubject.

Sample data can be

students            Subjects           StudentSubject
--------------      ---------          ----------------
ID  Name           SID  SName           ID   SID
--------------      ---------          ----------------
1  St1             1  Sub1               1    1
2  St2             2  Sub2                
                   3  Sub3                
                   4  Sub4                

So in above example student "St1" is enrolled in subjects "Sub1" .

I am able to create 3 views that can create new student, new subject and even new record in table StudentSubject.

But my question is how can I create records in table StudentSubject at the same time when I create record in table Student.

So my view can have fields like

ID, name, SubjectName

and if I enter

ID             3 
name           St3  
SubjectName    Sub2

and I click save, it should first create record in table Students and then in table StudentSubject based on subject selected.

So now the tables should look as below

students            Subjects           StudentSubject
--------------      ---------          ----------------
ID  Name           SID  SName           ID   SID
--------------      ---------          ----------------
1  St1             1  Sub1               1    1
2  St2             2  Sub2               3    2 
3  St3             3  Sub3                
                   4  Sub4   

Thank You.

Upvotes: 0

Views: 794

Answers (1)

Jakotheshadows
Jakotheshadows

Reputation: 1515

Without sharing any of your code it is hard to tell what your problem is. Here is my best guess at a solution without seeing any of your code:

using (var context = new MyContext())
{
  var myNewStudent = new Student()
  {
    //initialize your student
  };
  context.Students.Add(myNewStudent);
  context.SaveChanges();
  //get the identity column from the inserted student
  int id = myNewStudent.ID; 
  var myNewStudentSubject = new StudentSubject()
  {
    SID = id
  }
  context.StudentSubjects.Add(myNewStudentSubject);
  context.SaveChanges();
}

Perhaps you should explain what you mean by "at the same time" on these inserts, and why you think it is necessary.

Upvotes: 1

Related Questions