【问题标题】:asp.net mvc 5 create new rows in detail table at same time as master tableasp.net mvc 5 与主表同时在明细表中创建新行
【发布时间】:2015-09-08 20:05:28
【问题描述】:

所以我正在使用 asp.net mvc5 。我使用数据库优先方法来创建简单的 Web 应用程序。我的问题是如何在创建父记录时创建子记录。假设我有 3 个表,即 (1)Students (2)Subject 和 (3)StudentSubject。

样本数据可以

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

所以在上面的例子中,学生“St1”就读于科目“Sub1”。

我能够创建 3 个视图,可以在 StudentSubject 表中创建新学生、新学科甚至新记录。

但我的问题是如何在表 StudentSubject 中创建记录的同时在表 StudentSubject 中创建记录。

所以我的视图可以有类似的字段

身份证, 姓名, 主题名称

如果我进入

ID             3 
name           St3  
SubjectName    Sub2

我点击保存,它应该首先在学生表中创建记录,然后根据选择的主题在表 StudentSubject 中创建记录。

所以现在表格应该如下所示

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   

谢谢。

【问题讨论】:

  • 你试过什么?单击保存时,您是否至少创建了学生记录?
  • 感谢您的回复。是的,我可以独立创建 Student 和 StudentSubject。就像我说的问题是我想在创建学生记录的同时创建 StudentSubject 记录。
  • 如果对您有帮助,您能接受我的回答吗?

标签: asp.net asp.net-mvc asp.net-mvc-5


【解决方案1】:

如果不共享您的任何代码,就很难说出您的问题所在。这是我在没有看到任何代码的情况下对解决方案的最佳猜测:

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();
}

也许您应该在这些插页上解释“同时”是什么意思,以及为什么认为这是必要的。

【讨论】:

  • 谢谢杰克。 “同时”是指我想在创建学生记录时创建 StudentSubject。当然,我必须为正在创建的新学生选择科目。现在我首先创建学生。然后在不同的页面中,我选择新创建的学生,然后从科目列表中选择科目并保存。我会尝试在这里放一些代码。它的代码太多了。
  • 好吧,这个框架代码(一旦你添加了缺失的细节)将在 1 个请求中执行。你有什么不明白的地方吗?
  • 再次感谢杰克。我能够理解你的代码。只需要将整个东西(mvc)放在一起以确保它有效。很快就会留下反馈。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-25
  • 2012-07-24
  • 1970-01-01
  • 2021-12-14
  • 1970-01-01
  • 2019-07-11
相关资源
最近更新 更多